Django 注释 - 获取所有相关的属性 objects
Django annotate - get attribute of all related objects
我有这样一个模型:
# models.py
class A(Model):
...
class B(Model):
parent = ForeignKey(A)
comments = ForeignKey(Comments)
class Comments(Model):
title = CharField(...)
如何使用查询集的 annotate
方法,获取 B
与某些 A
查询集相关的评论的所有标题?
我试过了:
result = A.object.all().annotate(b_titles=F("b__comments__title"))
但它 returns 只有第一个 object。
FilteredRelation
也没有帮助 (FilteredRelation's condition doesn't support nested relations
)
我用 ArrayAgg
解决了这个问题 (https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/aggregates/)
- 仅使用 Postgres 可用。
我有这样一个模型:
# models.py
class A(Model):
...
class B(Model):
parent = ForeignKey(A)
comments = ForeignKey(Comments)
class Comments(Model):
title = CharField(...)
如何使用查询集的 annotate
方法,获取 B
与某些 A
查询集相关的评论的所有标题?
我试过了:
result = A.object.all().annotate(b_titles=F("b__comments__title"))
但它 returns 只有第一个 object。
FilteredRelation
也没有帮助 (FilteredRelation's condition doesn't support nested relations
)
我用 ArrayAgg
解决了这个问题 (https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/aggregates/)
- 仅使用 Postgres 可用。