簡體   English   中英

Django annotate - 獲取所有相關對象的屬性

[英]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(...)  

如何使用queryset的annotate方法,我可以獲得與某些A相關的B s評論的所有標題?

我試過了:

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

但它只返回第一個對象。

FilteredRelation也沒有幫助( FilteredRelation's condition doesn't support nested relations

我用ArrayAgghttps://docs.djangoproject.com/en/2.2/ref/contrib/postgres/aggregates/ )解決了這個問題 - 只能使用Postgres。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM