我用的是mongoengine

先 pip install mongoengine

编写ORM模型:

from mongoengine import Document, IntField, StringField, ListField, EmbeddedDocument, EmbeddedDocumentField, FloatField

class Course(EmbeddedDocument):
    subject = StringField(required=True)
    score = FloatField(required=True)

class Student(Document):
    no = IntField(required=True)
    name = StringField(required=True)
    examination_results = ListField(EmbeddedDocumentField(Course))

    meta = {'collection': 'student', 'indexes': [{'fields': ['+no']}]}

mongoDB信息:

mongodbinfo = {
    'host': 'IP',
    'port': 27017,
    'username': 'XX',
    'password': '**',
    'db': 'XX',
    'authentication_source': '认证数据库'
}

启动文件中:

from mongoengine import connect, disconnect

@app.on_event("startup")
async def connect_mongodb():
    connect(**mongodbinfo)

@app.on_event("shutdown")
async def disconnect_mongodb():
    disconnect()

views中增删改查:

# create
student=Student(no=1, name='xx',examination_results =[Course(subject='语文', score =90 ), Course(subject='数学', score =80 )])
student.save()

# query
student = Student.objects.filter(no=1).first()

# update
student = Student.objects.filter(no=1).first()
student.examination_results.append(Course(subject='英语', score =99))
student.save()

# delete
student.objects.filter(no=1).delete()

更多操作 见上面的官网文档

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐