仅添加一行代码,如何将Django与MongoDB结合使用。

by Siddy Zen

通过西迪禅

仅添加一行代码,如何将Django与MongoDB结合使用。 (How to use Django with MongoDB by adding just one line of code.)

To use MongoDB as your backend database in your Django project, just add this one line into your settings.py file:

要将MongoDB用作Django项目中的后端数据库 ,只需将这一行添加到settings.py文件中:

DATABASES = {   ‘default’: {      ‘ENGINE’: ‘djongo’,      ‘NAME’: ‘your-db-name’,   }}

It’s that simple!

就这么简单!

Next, login to your admin home (localhost:8000/admin/) and start adding “embedded documents” into MongoDB using the Admin GUI:

接下来,登录到您的管理主页(localhost:8000 / admin /),然后开始使用Admin GUI将“嵌入式文档”添加到MongoDB中:

In October, 2017 MongoDB finished up the final step in going public, pricing its IPO at $24 and raising $192 million in the process. The company's finances have been growing steadily:

2017年10月,MongoDB完成了上市的最后一步,将其IPO定价为24美元,并在此过程中筹集了1.92亿美元。 该公司的财务一直稳定增长:

MongoDB provides open-sourced database software. This is very helpful to early-stage startups looking to launch while being constrained by tight budgets. A review of Google search trends for MongoDB revealed a steady increase in interest.

MongoDB提供开源数据库软件。 这对于希望在预算紧张的情况下启动的早期创业公司非常有帮助。 对MongoDB的Google搜索趋势进行的审​​查显示,人们的兴趣持续增长。

MongoDB has increasingly becoming a popular database software to work with. Databases and Database management systems (DBMS) have existed for more than five decades. They emerged in the early 1960s, and the most popular flavor was the relational database system.

MongoDB越来越成为一种流行的数据库软件。 数据库和数据库管理系统(DBMS)已经存在了五十多年。 它们出现在1960年代初,最受欢迎的形式是关系数据库系统。

But MongoDB goes around calling itself a “non-relational” database system, and has been making tall claims about its approach to store data. So, what exactly is the BIG deal here?

但是MongoDB自称是“非关系”数据库系统,并且一直对其存储数据的方法提出很高的要求。 那么,这里的大笔交易到底是什么?

MongoDB与SQL (MongoDB vs SQL)

Pretty much all relational database systems use the Structured Query Language (SQL) (or a tweaked version of it) to communicate with the data management software. Several university courses are solely dedicated to the understanding and mastery of the SQL syntax.

几乎所有关系数据库系统都使用结构化查询语言(SQL)(或其调整版本)与数据管理软件进行通信。 一些大学课程专门致力于SQL语法的理解和掌握。

SQL had become the de-facto language for working with any database (DB) software, proprietary or open source. Then MongoDB came along and decided to show utter disregard to this ancient language of power and introduced query syntax of its own.

SQL已经成为事实上的语言,可用于任何专有或开放源代码的数据库(DB)软件。 然后,MongoDB出现并决定完全无视这种古老的功能语言,并介绍了它自己的查询语法。

The language is that of Mordor which I will not utter here. In the common tongue, it says, “One ring to rule them all. One ring to find them. One ring to bring them all and in the darkness bind them.”
语言是Mordor的语言,在这里我不会说。 用通俗的语言说:“一个环来统治所有人。 一环找到他们。 一环将它们带到黑暗中,将它们束缚起来。”

-Gandalf (from The lord of the rings)

-甘道夫( 来自指环王)

MongoDB Schemaless vs SQL Schema: In an SQL database, it’s impossible to add data until you define tables and field types in what’s referred to as a schema. In a MongoDB database, data can be added anywhere, at any time. There’s no need to specify a document design or even a collection up-front.

MongoDB Schemaless与SQL Schema:在SQL数据库中,除非您在所谓的模式中定义表和字段类型,否则无法添加数据。 在MongoDB数据库中,可以随时随地添加数据。 无需预先指定文档设计甚至是集合。

MongoDB Documents vs SQL Tables: SQL databases provide a store of related data tables. Every row is a different record. The design is rigid: you cannot use the same table to store different information or insert a string where a number is expected.

MongoDB文档与SQL表: SQL数据库提供了相关数据表的存储。 每行都是不同的记录。 设计是严​​格的:您不能使用同一张表存储不同的信息,也不能在需要数字的地方插入字符串。

The MongoDB database stores JSON-like field-value pair documents. Similar documents can be stored in a collection, which is analogous to an SQL table. However, you can store any data you like in any document — MongoDB won’t complain. SQL tables create a strict data template, so it’s difficult to make mistakes. MongoDB is more flexible and forgiving, but being able to store any data anywhere can lead to consistency issues.

MongoDB数据库存储类似JSON的字段-值对文档。 可以将类似的文档存储在类似于SQL表的集合中。 但是,您可以在任何文档中存储所需的任何数据-MongoDB不会抱怨。 SQL表创建了严格的数据模板,因此很难出错。 MongoDB更加灵活和宽容,但是能够将任何数据存储在任何地方都可能导致一致性问题。

There is a plethora of online content available that argues that MongoDB is not a superset of SQL. Applications that run on SQL cannot be ported to MongoDB. I am going out on a limb here to claim that, in the context of Django, MongoDB is a superset of SQL.

有大量在线内容可供使用,它们认为MongoDB不是SQL的超集。 无法将基于SQL运行的应用程序移植到MongoDB。 我在这里断言,在Django的上下文中, MongoDB是SQL的超集

So why does the popular belief, that MongoDB is not a superset of SQL, exist to begin with?

那么为什么从一开始就存在普遍的信念,即MongoDB不是SQL的超集?

MongoDB requires Denormalization of data: In MongoDb there is no JOIN support. This means we will have to denormalize our documents. Denormalized documents leads to faster queries, but updating the document field information in multiple denormalized documents will be significantly slower.

MongoDB需要对数据进行非规范化:在MongoDb中,没有JOIN支持。 这意味着我们将不得不对文档进行非规范化。 非规范化文档会导致更快的查询,但是更新多个非规范化文档中的文档字段信息将明显变慢。

There are no JOINs: SQL queries offer a powerful JOIN clause. We can obtain related data in multiple tables using a single SQL statement. In non-relational databases like MongoDB, there are no JOINs like there would be in relational databases. This means you need to perform multiple queries and join the data manually within your code.

没有JOIN :SQL查询提供了强大的JOIN子句。 我们可以使用一个SQL语句在多个表中获取相关数据。 在非关系数据库(如MongoDB)中,没有像在关系数据库中那样的JOIN。 这意味着您需要执行多个查询并在代码中手动联接数据。

No Transactions: In SQL databases, two or more updates can be executed in a transaction — an all-or-nothing wrapper that guarantees success or failure. If we execute two updates individually, one could succeed and the other fail — thus leaving our figures out of sync. Placing the same updates within a transaction ensures either both succeed or both fail.

无事务处理:在SQL数据库中,可以在一个事务中执行两个或多个更新-保证成功或失败的全有或全无包装。 如果我们分别执行两个更新,那么一个更新可能成功而另一个失败—这样会使我们的数据不同步。 在事务中放置相同的更新可确保成功或失败。

No foreign key constraints: Most SQL databases allow you to enforce data integrity rules using foreign key constraints. This ensure all rows have a valid foreign key for code that matches one entry in the join table, and makes sure that a record from the join table is not removed if one or more rows still refer to them.

无外键约束:大多数SQL数据库允许您使用外键约束来实施数据完整性规则。 这样可以确保所有行都具有与联接表中的一个条目匹配的代码的有效外键,并确保如果仍然有一行或更多行引用联接表中的记录,则不会删除该记录。

The schema enforces these rules for the database to follow. It’s impossible for developers or users to add, edit, or remove records, which could result in invalid data or orphan records. The same data integrity options are not available in MongoDB. You can store what you want regardless of any other documents. Ideally, a single document would be the sole source of all information about an item.

该模式强制这些规则供数据库遵循。 开发人员或用户无法添加,编辑或删除记录,这可能导致无效的数据或孤立的记录。 相同的数据完整性选项在MongoDB中不可用。 您可以存储所需的内容,而不管其他任何文档。 理想情况下,单个文档将是有关项目的所有信息的唯一来源。

对数据库模型的需求 (The need for a Database Model)

Objects are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects. While objects are a good way to represent data, a problem arises when we want to make the data persistent. The amount of data could be huge, and it must be retrieved from the persistent memory quickly and efficiently. This database software must be used to store the objects. A possible database software is a relational, SQL-based database software.

对象是Python对数据的抽象。 Python程序中的所有数据都由对象或对象之间的关系表示。 尽管对象是表示数据的好方法,但是当我们要使数据持久化时会出现问题 数据量可能很大,因此必须快速有效地从持久性内存中检索数据。 该数据库软件必须用于存储对象。 可能的数据库软件是基于SQL的关系数据库软件。

An object-relational mapper (ORM) is a code library that automates the transfer of data stored in relational database tables into Python objects that are used in Python code. ORMs provide a high-level abstraction upon a relational database that allows a developer to write Python code instead of SQL syntax to create, read, update and delete data and schemas in their database. Developers can use the Python programming language with which they are comfortable instead of writing SQL statements or stored procedures.

对象关系映射器(ORM)是一个代码库,可自动将关系数据库表中存储的数据传输到Python代码中使用的Python对象中。 ORM在关系数据库上提供了高级抽象,允许开发人员编写Python代码而不是SQL语法来创建,读取,更新和删除其数据库中的数据和模式。 开发人员可以使用自己喜欢的Python编程语言,而不必编写SQL语句或存储过程。

An example of an ORM framework for Python is SQLAlchemy. The SQLAlchemy ORM presents a method of associating user-defined Python classes with database tables, and instances of those classes (objects) with rows in their corresponding tables. It includes a system that transparently synchronizes all changes in state between objects and their related rows. Web frameworks like flask use SQLAlchemy for storing data persistently.

SQLAlchemy是Python的ORM框架的一个示例。 SQLAlchemy ORM提出了一种将用户定义的Python类与数据库表相关联的方法,并将这些类(对象)的实例与它们对应的表中的行相关联。 它包括一个透明地同步对象及其相关行之间的所有状态变化的系统。 诸如flask之类的Web框架使用SQLAlchemy持久存储数据。

Django ORM: Django comes with its own ORM or model for short. The model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing. Generally, each model maps to a single database table. The Django Model also make it possible to switch between various relational databases such as Oracle SQL, MySQL, or MSSQL.

Django ORM: Django带有自己的ORM或模型。 该模型是有关您的数据的唯一权威信息。 它包含要存储的数据的基本字段和行为。 通常,每个模型都映射到单个数据库表。 Django模型还使在各种关系数据库(例如Oracle SQL,MySQL或MSSQL)之间切换成为可能。

使用Django ORM将文档添加到MongoDB中 (Using Django ORM to add documents into MongoDB)

Let’s say you want to create a blogging platform using Django with MongoDB as your backend.

假设您要使用MongoDB作为后端使用Django创建博客平台。

In your Blog app/models.py file define the BlogContent model:

在您的Blog app/models.py文件中,定义BlogContent模型:

from djongo import modelsfrom djongo.models import forms
class BlogContent(models.Model):    comment = models.CharField(max_length=100)    author = models.CharField(max_length=100)    class Meta:        abstract = True

To access the model using Django Admin, you will need a Form definition for the above model. Define it as shown below:

要使用Django Admin访问模型,您将需要上述模型的Form定义。 如下所示定义它:

class BlogContentForm(forms.ModelForm):    class Meta:        model = BlogContent        fields = (            'comment', 'author'        )

Now “embed” your BlogContent inside a BlogPost using the EmbeddedModelField as below:

现在,“嵌入”你BlogContent一个内部BlogPost使用EmbeddedModelField如下:

class BlogPost(models.Model):    h1 = models.CharField(max_length=100)    content = models.EmbeddedModelField(        model_container=BlogContent,        model_form=BlogContentForm    )

That’s it you are set! Fire up Django Admin on localhost:8000/admin/ and this is what you get:

就是这样,您已经设置好了! 在localhost:8000 / admin /上启动Django Admin,这是您得到的:

Next, assume you want to “extend” the author field to contain more than just the name. You need both a name and email. Simply make the author field an “embedded” field instead of a “char” field:

接下来,假设您要“扩展”作者字段以包含更多的名称。 您需要一个名称和电子邮件。 只需将作者字段设置为“嵌入”字段而不是“字符”字段即可:

class Author(models.Model):    name = models.CharField(max_length=100)    email = models.CharField(max_length=100)    class Meta:        abstract = Trueclass AuthorForm(forms.ModelForm):    class Meta:        model = Author        fields = (            'name', 'email'        )
class BlogContent(models.Model):    comment = models.CharField(max_length=100)    author = models.EmbeddedModelField(        model_container=Author,        model_form=AuthorForm    )    class Meta:        abstract = True

If a blog post has multiple content from multiple authors, define a new model:

如果博客文章具有多个作者的多个内容,请定义一个新模型:

class MultipleBlogPosts(models.Model):    h1 = models.CharField(max_length=100)    content = models.ArrayModelField(        model_container=BlogContent,        model_form=BlogContentForm    )

Fire up Django Admin with the new changes and you have:

使用新更改启动Django Admin,您将:

集成Django和MongoDB的方法。 (Ways to integrate Django and MongoDB.)

The Django ORM consists of multiple Abstraction Layers stacked on top of each other.

Django ORM由多个彼此堆叠的抽象层组成。

As a web developer, you can take up the challenge of connecting Django to MongoDB in two ways. Take a look at the Django framework stack above to guess the possible entry points.

作为Web开发人员,您可以通过两种方式来应对将Django连接到MongoDB的挑战。 看一下上面的Django框架堆栈,猜测可能的入口点。

使用与MongoDB兼容的模型 (Use a MongoDB compatible model)

You can completely avoid using the “batteries included” Django models in your project. Instead, use a third party framework like MongoEngine or Ming in you Django projects.

您可以完全避免在项目中使用“包含电池”的Django模型。 相反,请在您的Django项目中使用第三方框架,例如MongoEngine或Ming。

Choosing a different Model means you miss out on:

选择其他模型意味着您会错过:

You’d ramp down on the expertise of existing Django models and ramp up on the new model framework. But perhaps the biggest drawback is that your project can’t use any of Django’s contrib models! Forget about using Admin, Sessions, Users, Auth, and other contrib modules for your project.

您将减少现有Django模型的专业知识,并增加新的模型框架。 但是,最大的缺点可能是您的项目不能使用Django的任何contrib模型! 无需再为项目使用Admin,Sessions,Users,Auth和其他contrib模块。

Some of these disadvantages are offset by forking a new branch of Django itself. Django-nonrel is an independent branch of Django that adds NoSQL database support to Django. Django-nonrel allows for writing portable Django apps. However, the admin interface does not work fully. There is no active development taking place on the Django-nonrel project.

其中的一些缺点可以通过创建Django本身的新分支来弥补。 Django-nonrel是Django的独立分支,为Django添加了NoSQL数据库支持。 Django-nonrel允许编写便携式Django应用程序。 但是,管理界面无法完全正常工作。 Django-nonrel项目上没有任何活跃的开发。

Django MongoDB Engine is another MongoDB backend for Django which is a fork off the MongoEngine ODM.

Django MongoDB EngineDjango的另一个MongoDB后端,它是MongoEngine ODM的分支。

Django SQL到MongoDB转译器— Djongo (Django SQL to MongoDB transpiler — Djongo)

Another approach is to translate Django SQL query syntax generated by the Django ORM into pymongo commands. Djongo is one such SQL to MongoDB query compiler. It translates every SQL query string into a mongoDB query document. As a result, all Django models and related modules work as is. With this approach, you gain on:

另一种方法是将Django ORM生成的Django SQL查询语法转换为pymongo命令。 Djongo是一种这样SQL到MongoDB查询编译器。 它将每个SQL查询字符串转换为mongoDB查询文档。 结果,所有Django模型和相关模块都按原样工作。 通过这种方法,您将获得:

  • Reuse of Django Models: Django is a stable framework with continuous development and enhancements. The Django ORM is quite extensive and feature-rich. Defining a third party ORM to work with MongoDB means reproducing the entire Django ORM again. The new ORM needs to constantly align with the Django ORM. Several Django features will never make it into the third party ORM. The idea with Djongo is to reuse existing Django ORM features by finally translating SQL queries to MongoDB syntax.

    重用Django模型: Django是一个稳定的框架,具有持续的开发和增强功能。 Django ORM非常广泛且功能丰富。 定义第三方 ORM以与MongoDB一起使用意味着再次再现整个Django ORM。 新的ORM需要不断与Django ORM保持一致。 Django的一些功能永远不会使它成为第三方ORM。 Djongo的想法是通过最终将SQL查询转换为MongoDB语法来重用现有的Django ORM功能。

  • SQL syntax will never change regardless of future additions to Django. By using Djongo, your project is now future proof!

    不管将来对Django的添加是什么, SQL语法都不会改变 。 通过使用Djongo,您的项目现在可以面向未来!

使Django与MongoDB一起使用 (Making Django work with MongoDB)

Emulating Schema in MongoDB: While there is no schema support in MongoDB, this can be emulated. Djongo provides the schema support required in Django by using and defining a combination of MongoDB validator rules and by creating a __schema__ collection. The __schema__ collection stores information for supporting features like the SQL AUTOINCREMENT key.

在MongoDB中模拟架构:尽管MongoDB中没有架构支持,但是可以对其进行仿真。 Djongo通过使用和定义MongoDB验证程序规则的组合以及创建__schema__集合,来提供Django中所需的模式支持。 __schema__集合存储用于支持功能的信息,例如SQL AUTOINCREMENT键。

JOIN support in MongoDB: In version 3.2, MongoDB introduced the $lookup operator. It performs a left outer join to a collection in the same database to filter in documents from the “joined” collection for processing. The $lookup stage does an equality match between a field from the input documents with a field from the documents of the “joined” collection.

MongoDB中的JOIN支持:在3.2版中,MongoDB引入了$lookup运算符。 它对同一数据库中的集合执行左外部联接,以过滤“联接”集合中的文档以进行处理。 $lookup阶段在输入文档中的字段与“ joined”集合的文档中的字段之间进行相等匹配。

To each input document, the $lookup stage adds a new array field whose elements are the matching documents from the “joined” collection. The $lookup stage passes these reshaped documents to the next stage.

在每个输入文档中, $lookup阶段添加一个新的数组字段,其元素是“ joined”集合中的匹配文档。 $lookup阶段将这些经过重整的文档传递到下一个阶段。

Djongo uses the $lookup aggregation operator to perform all Django related JOIN queries. This is how it makes admin and other contrib modules work as is.

Djongo使用$lookup聚合运算符执行所有与Django相关的JOIN查询。 这就是使admin和其他contrib模块按原样工作的方式。

Transaction support in MongoDB: Despite the power of single-document atomic operations, there are cases that require multi-document transactions. When executing a transaction composed of sequential operations, certain issues arise, wherein if one operation fails, the previous operation within the transaction must “rollback” to the previous state — that is, the “all or nothing.”

MongoDB中的事务支持:尽管单文档原子操作具有强大的功能,但在某些情况下仍需要多文档事务。 当执行由顺序操作组成的事务时,会出现某些问题,其中,如果一个操作失败,则事务中的前一个操作必须“回滚”到前一个状态,即“全有或全无”。

For situations that require multi-document transactions, Djongo implements the two-phase commit pattern to provide support for these kinds of multi-document updates. Using two-phase commit ensures that data is consistent and, in case of an error, the state that preceded the transaction is recoverable.

对于需要多文档事务的情况,Djongo实现了两阶段提交模式,以支持这些类型的多文档更新。 使用两阶段提交可确保数据一致,并且在发生错误的情况下,可恢复事务之前的状态。

Djongo comes with its own set of compromises, though. So what are the disadvantages of opting to use Djongo for your Django project?

不过,Djongo拥有自己的一系列折衷方案。 那么,在您的Django项目中选择使用Djongo有什么缺点呢?

Performance: The Django ORM does the heavy lifting of converting complex object manipulations to standard SQL query strings. If your backend database was SQL-based, you could pass this query string directly to it with almost no post-processing. With Djongo, however, the query string will now have to be converted into a MongoDB query document.

性能: Django ORM繁重的工作将复杂的对象操作转换为标准SQL查询字符串。 如果您的后端数据库是基于SQL的,则可以几乎不进行任何后处理就直接将此查询字符串传递给它。 但是,使用Djongo,现在必须将查询字符串转换为MongoDB查询文档。

This is going to require some CPU cycles. But if extra CPU cycles are really such a problem, you probably shouldn’t be using Python in the first place.

这将需要一些CPU周期。 但是,如果额外的CPU周期确实是个问题,那么您一开始就不应该使用Python。

结论 (Conclusion)

I took you through several ways of integrating Django with MongoDB. You will find a multitude of online literature describing the MongoEngine and other variants for doing this.

我为您介绍了将Django与MongoDB集成的几种方法。 您会发现许多描述MongoEngine及其相关变体的在线文献。

I focused on Djongo which is a new connector that makes this possible in a different way. It is easy to use and makes the process of migrating from a SQL backend to MongoDB very simple, by adding just one line of code.

我专注于Djongo ,这是一个新的连接器,以不同的方式使之成为可能。 它很容易使用, 只需添加一行代码即可使从SQL后端迁移到MongoDB的过程非常简单。

翻译自: https://www.freecodecamp.org/news/using-django-with-mongodb-by-adding-just-one-line-of-code-c386a298e179/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值