【英文】Django项目中连接MongoDB

Preface

Notes on connecting MongoDB in Django projects

Download Dependencies

1
pip3 install pymongo

Modify Global Configuration

  • Add MongoClient configuration after the DATABASES configuration in the global configuration
<project_name>/<project_name>/settings.py
1
2
3
4
5
6
from pymongo import MongoClient

MONGOCLIENT = MongoClient(
host='127.0.0.1',
port='27017'
)

MongoDB Client

Encapsulate MongoDB Client

  • Create the mongo_models.py configuration file in the root directory of the sub-application

<dbname>: Specify the name of the connected database
<collection_name>: Specify the name of the collection to operate on

<project_name>/<app_name>/mongo_models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from django.conf import settings

connect = settings.MONGOCLIENT['<dbname>']
class User(object):
db = connect['<collection_name>']

@classmethod
def insert(cls, **params):
return cls.db.insert(params)

@classmethod
def get(cls, **params):
return cls.db.find_one(params)

@classmethod
def gets(cls, **params):
return cls.db.find(params)

@classmethod
def update(cls, _id, **params):
return cls.db.update({'_id', _id}, {'$set': params})

Using MongoDB Client

1
2
3
from app.mongo_models import User

users = User.gets()

MongoDB Table Association

Download Dependencies

1
pip3 install mongoengine

Create a Database Mapping

  • Create the mongo_engine.py configuration file in the root directory of the sub-application

<dbname>: Specify the name of the connected database

Attributes:

required: Whether it is empty or not
max_length: String length

<project_name>/<app_name>/mongo_engine.py
1
2
3
4
5
6
from mongoengine import connect, Document, StringField, IntField

connect('<dbname>', host='127.0.0.1', port='27017')
class User(Document):
id = IntField(required=False)
name = StringField(max_length=5)

Multiple Table Association

One-to-One

<project_name>/<app_name>/mongo_engine.py
1
2
3
4
5
6
7
8
9
10
11
from mongoengine import connect, Document, StringField, IntField, ReferenceField

connect('<dbname>', host='127.0.0.1', port='27017')
class User(Document):
id = IntField(required=False)
name = StringField(max_length=5)

# One-to-One association
class OneToOne(Document):
id = IntField(required=False)
user = ReferenceField(User)

CRUD Operations

Import Modules

  • If you need to use classes from mongo_engine.py in views.py, you need to import the modules first
<project_name>/<app_name>/views.py
1
from .mongo_engine import User

Add Data

Method 1: Use the built-in methods directly

1
User.objects.create(field_name=field_value)

Method 2: Use the save() method

1
2
user = User(field_name=field_value)
user.save()

Completion

References

Bilibili-Turing Academy Tutorial