【问题标题】:Getting referenced object's ID without fetching it获取引用对象的 ID 而不获取它
【发布时间】:2012-11-28 11:09:12
【问题描述】:

假设我有一个名为 Post 的 MongoEngine 文档类:

class Post(Document):
    author = ReferenceField(Author)

如何在不获取实际作者对象的情况下获取帖子的作者 ID?

如果我写

print post.author.id

MongoEngine 对数据库进行查询以获取作者对象。我会写

print post._data["author"]

如果 author 字段已被取消引用,则返回 Author 对象,否则返回 DBRef 对象。

有这样做的标准方法吗?

【问题讨论】:

    标签: python mongodb mongoengine


    【解决方案1】:

    怎么样:

    post.to_mongo()['author'].id
    

    【讨论】:

    • 是的,应该可以。谢谢你。但是,除了给我 id 之外,它在每次访问中都会做很多事情。为了效率,我宁愿将self._data["author"].id封装在 Post 类中的一个方法中。
    猜你喜欢
    • 1970-01-01
    • 2019-11-09
    • 2013-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-27
    • 2020-11-28
    • 1970-01-01
    相关资源
    最近更新 更多