安装配置(支持Python3)
安装mongoengine
1 | pip install mongoengine |
新建MongodbModel
新建model.py文件1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16mongodb = 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.py1
2
3INSTALLED_APPS = [
'rest_framework_mongoengine'
]
models.py1
2
3
4
5
6
7
8class ProductSerializer(DocumentSerializer):
access = serializers.ListField()
class Meta:
model = Product
fields = (
'access',
)