【问题标题】:Create Pony ORM entity without fetching related objects?创建 Pony ORM 实体而不获取相关对象?
【发布时间】:2020-02-14 09:56:37
【问题描述】:

我最近开始使用 Pony ORM,我觉得它很棒。尽管官方网站上有详细的 api 文档,但我很难处理关系。特别是我想插入一个新实体,它是集合的一部分。但是,如果不先获取相关对象,我似乎无法找到创建实体的方法:

post = Post(
    #author = author_id, # Python complains about author's type, which is int and should be User
    author = User[author_id], # This works, but as I understand it actually fetches the user object
    #author = User(id=author_id), # This will try and (fail to) create a new record for the User table when I commit, am I right?
    # ...
)

表中最后只插入了id的值,为什么我只需要id就取整个对象呢?

编辑

我快速浏览了 Pony ORM 源​​代码,使用反向实体的主键应该可以工作,但即使在这种情况下,我们最终也会调用 _get_by_raw_pkval_ 从本地缓存或数据库中获取对象,因此可能是不可能的。

【问题讨论】:

    标签: python mysql flask orm ponyorm


    【解决方案1】:

    它是内部 API 的一部分,也不是 Pony 假定您使用它的方式,但实际上您可以使用 author = User._get_by_raw_pkval_((author_id,)),如果您确定您拥有具有这些 id 的那些对象。

    【讨论】:

    • 但是_get_by_raw_pkval((author_id,)) 会立即从数据库中获取对象,不是吗?
    • @Sneppy 不,它没有。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    • 2018-12-10
    • 1970-01-01
    相关资源
    最近更新 更多