Overview
在本指南中,您可以学习;了解如何配置 Django 项目与MongoDB的连接。
连接配置
安装 Django MongoDB后端并创建项目后,您可以通过修改项目的 settings.py
文件中的 DATABASES
设置来配置与MongoDB的连接。
提示
要学习;了解如何安装 Django MongoDB后端和创建 Django项目,请访问 入门教程。
将 DATABASES
设置为包含 default
键的字典,如以下代码所示:
DATABASES = { "default": { # Specify nested dictionary keys here }, }
要配置 default
键,请将嵌套字典指定为其值。 该嵌套字典具有以下键:
键 | 说明 |
---|---|
引擎 | 用于连接的后端驾驶员。 将此键设置为 |
主机 | The hostname. For localhost connections, this key is optional. For SRV connections, you must include a scheme prefix ( mongodb+srv:// ).You can also specify a connection URI in this key. For more information,
see Automatically Configure Database Settings. To specify more than one host, include all hostnames in one string. Use
a comma to separate each hostname. Example: "HOST": "mongodb://mongos0.example.com:27017,mongos1.example.com:27017" |
名称 | 要使用的数据库。 |
用户 | 如果您的连接需要身份验证,则用于对数据库进行身份验证的用户名。 |
PASSWORD | 如果您的连接需要身份验证,则数据库用户的密码。 |
端口 | The port number on which the database server is listening. The default
port is 27017 .For MongoDB Atlas connections, this key is optional. |
选项 | A dictionary of additional connection options for the database. This key is optional. To see a full list of connection options that you can set in the OPTIONS key,
see the optional parameters for MongoClient
in the PyMongo API documentation. |
本部分介绍如何使用 DATABASES
设置通过以下方式配置连接:
自动配置数据库设置
重要
在 v5.2.1 中添加
Django MongoDB后端 v5.2.1添加了对在嵌套的 HOST
键中指定连接 URI 的支持。如果使用以前的版本,仍可手动配置连接或使用parse_uri()函数。
要在连接 URI 中指定连接设置,设立以下嵌套的 default
键:
ENGINE
:设置为"django_mongodb_backend"
。HOST
:设置为您的连接 URI。NAME
:设置为要使用的数据库的名称。
上一节中描述的所有其他键都是可选的。
例子
此示例仅使用 ENGINE
、HOST
和 NAME
键来配置与MongoDB的连接。DATABASES
设置执行以下操作:
为用户名名为
my_user
、密码为my_password
的数据库用户提供身份验证信息将
retryWrites
连接选项设置为true
,这会将驾驶员配置为在某些写入操作失败时自动重试这些写入操作将
w
连接选项设置为majority
,这会将驾驶员配置为在执行写入操作之前等待大多数副本集成员的确认将数据库设置为
my_database
DATABASES = { "default": { "ENGINE": "django_mongodb_backend", "HOST": "mongodb+srv://my_user:my_password@cluster0.example.mongodb.net/?retryWrites=true&w=majority", "NAME": "my_database", }
注意
如果您在 DATABASES
设置中指定其他键,则这些键中的值会覆盖从连接 URI 解析的任何冲突值。
手动配置数据库设置
您可以通过 default
键指定连接信息来手动配置连接设置。
例子
此示例使用字典键配置与上一示例相同的数据库连接:
DATABASES = { "default": { "ENGINE": "django_mongodb_backend", "HOST": "mongodb+srv://cluster0.example.mongodb.net", "NAME": "my_database", "USER": "my_user", "PASSWORD": "my_password", "PORT": 27017, "OPTIONS": { "retryWrites": "true", "w": "majority", }, }, }
更多信息
要查看配置MongoDB 数据库连接的示例项目,请参阅入门教程中的配置MongoDB连接步骤。
要学习;了解有关 Django 设置的更多信息,请参阅 Django 文档中的设置。