【问题标题】:Django: Filtering foo_set via a custom property?Django:通过自定义属性过滤 foo_set?
【发布时间】:2010-01-13 22:57:37
【问题描述】:

我有一个名为 Product 的模型,它有一个自定义属性:

def _get_active(self):
    o = get_option()
    if self.date_expiration == None:
        return True
    if self.date_expiration <= o.working_month:
        return False
    return True
active = property(_get_active)

...在我的一种方法中,我有这一行:

products = g.product_set.filter(active__exact=True)

但尽管(我认为)我已经正确设置了属性,但上面的行给了我“无法将关键字 'active' 解析为字段。”我在这里错过了什么?

提前致谢。

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    您只能查询实际字段,不能查询属性。

    【讨论】:

    • for product in (x for x in g.product_set.iterator() if x.active):
    【解决方案2】:

    扩展 Ignacio 的答案,您可以这样做:

    products = [x for x in g.product_set.iterator() if x.active]
    

    虽然这会非常低效,因为您必须加载x.product_set 中的每条记录。

    【讨论】:

      猜你喜欢
      • 2020-12-19
      • 2015-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-01
      • 2022-11-18
      • 1970-01-01
      相关资源
      最近更新 更多