Django Mongodb配置

安装配置(支持Python3)

安装mongoengine

1
pip install mongoengine

新建MongodbModel

新建model.py文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
mongodb = connect(
'idea',
host='localhost',
port=27017,
username='',
password='',
authentication_source='admin',
authentication_mechanism='SCRAM-SHA-1'
)

class Product(Document):
_id = fields.ObjectId()
access = fields.ListField()

# 指明连接数据库的哪张表
meta = {'collection': 'product'}

需要注意:Product一定要声明对应product表的所有字段(能多不能少),否则报错。

Serializer

使用django-rest-framework-mongoengine

1
pip install django-rest-framework-mongoengine

settings.py

1
2
3
INSTALLED_APPS = [
'rest_framework_mongoengine'
]

models.py

1
2
3
4
5
6
7
8
class ProductSerializer(DocumentSerializer):
access = serializers.ListField()

class Meta:
model = Product
fields = (
'access',
)