【问题标题】:Adding custom id field in flask/mongoengine document在烧瓶/mongoengine 文档中添加自定义 id 字段
【发布时间】:2016-05-31 14:47:56
【问题描述】:

我正在将一个应用程序从 Django/MySQL 改成 flask/mongo-engine,并且在创建带有 id 字段的模型时遇到了问题。这是一个示例模型:

class Location(db.Document):
    id = db.IntField(unique=True)
    name = db.StringField(max_length=200, required=True)
    # other fields in the document ...

为了向后兼容,我需要按原样命名的字段id。这曾经在 MySQL 中运行良好,但 mongo-engine 给出了 ValidationError -- Field is required: ['id'] Invalid Object ID: ['auto_id_0'] 用于上述模型的文档。

我也尝试使用db_field 参数,如

id = db.IntField(db_field='l_id', unique=True)

...但无济于事。

请注意,我无意覆盖 mongodb 的默认 ObjectID 字段。除了在反序列化时重命名该字段之外,还有其他解决方法吗?

【问题讨论】:

    标签: flask mongoengine flask-mongoengine


    【解决方案1】:

    试试

    class Location(db.Document):
        myid = db.IntField(db_field='id', unique=True)
        name = db.StringField(max_length=200, required=True)
        # other fields in the document ...
    

    并像字段名为 myid 一样对其进行操作。

    Location.objects.create(myid=real_id)
    Location.objects.filter(myid=real_id)
    

    【讨论】:

    • 这将覆盖存储 ObjectID 的默认 id 字段。无论如何,我尝试了很多并询问了很多,但没有找到可以保留原始 id 字段以及添加名为“id”的应用程序级模型字段和其他一些数据库字段名称的方法。所以我最终在模型中添加了一个名为 l_id 的新字段,并在我的 API 响应中对其进行了序列化。
    • 是的。我终于意识到文档将 _id 复制到 mongoengine 的 id 字段中,但是我为 db_field 指定了自定义名称
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 2019-02-27
    • 1970-01-01
    • 2021-01-13
    相关资源
    最近更新 更多