set value for __id for mongbd using flask_MongoEngine

拟墨画扇 提交于 2020-01-24 19:32:09

问题


How can I set value for __id field in mongo db using flask-MongoEngine? here is my code

db = MongoEngine(app)

class Book(db.Document):
    id = db.IntField(required = True)
    title = db.StringField(required = True)
    author = db.StringField(required = True)

def Create_record(title:str,author:str):
    book = Book()
    book.id = "123"
    book.title = title
    book.author = author

book.save()

回答1:


The easiest is to rely on the auto-generated id's from MongoDB (ObjectID) which encapsulates a timestamp so it's quite handy. If you don't specify any primary key field in your model, MongoEngine adds id behind the scenes.

This would be defined as:

class Book(Document):
    title = StringField()

book = Book(title='foo')
book.save()

Which is equivalent to

class Book(Document):
    id = ObjectIdField(default=bson.ObjectId, primary_key=True)
    title = StringField()

book = Book(title='foo')    # MongoEngine takes care of the id
book.save()

If for some reason you want an auto-increment integer, instead of an object id, you can achieve this easily with MongoEngine's SequenceField:

class Book(Document):
    id = SequenceField(primary_key=True)
    title = StringField()

book = Book(title='foo')    # MongoEngine takes care of the id
book.save()

Or, if you really want to manage the primary key yourself, then you can do it with

class Book(Document):
    id = IntField(primary_key=True)
    title = StringField()
    author = StringField()

book = Book(id=123, title='foo')
book.save()

What was missing in your example was the primary_key=True in the field definition



来源:https://stackoverflow.com/questions/59510616/set-value-for-id-for-mongbd-using-flask-mongoengine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!