fastAPI使用mongoDB
我用的是mongoengine先 pip install mongoengine编写ORM模型:from mongoengine import Document, IntField, StringField, ListField, EmbeddedDocument, EmbeddedDocumentField, FloatFieldclass Course(EmbeddedDocument):su
·
我用的是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()
更多操作 见上面的官网文档
更多推荐
已为社区贡献3条内容
所有评论(0)