【问题标题】:Django annotate - get attribute of all related objectsDjango annotate - 获取所有相关对象的属性
【发布时间】:2019-06-05 11:37:12
【问题描述】:

我有这样的模型:

# models.py
class A(Model):
    ...

class B(Model):
    parent = ForeignKey(A)
    comments = ForeignKey(Comments)

class Comments(Model):
    title = CharField(...)  

如何使用queryset的annotate方法,获取Bs'cmets的所有title与一些Aqueryset相关?

我试过了:

result = A.object.all().annotate(b_titles=F("b__comments__title"))

但它只返回第一个对象。

FilteredRelation 也没有帮助 (FilteredRelation's condition doesn't support nested relations)

【问题讨论】:

    标签: python django python-3.x django-models django-2.0


    【解决方案1】:

    我用ArrayAgg (https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/aggregates/) 解决了这个问题 - 只能使用 Postgres。

    【讨论】:

      猜你喜欢
      • 2016-10-20
      • 1970-01-01
      • 1970-01-01
      • 2011-01-15
      • 1970-01-01
      • 1970-01-01
      • 2011-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多