我在 Django(DRF) 中获取注释字段时遇到问题。
比如有两种型号,叫AA、BB。
class AA(models.Model):
name = models.CharField()
class BB(models.Model):
parent = models.ForeignKey(AA, related_name="BB")
name2 = models.CharField()
然后,我想获取列表 AA,其注释字段称为
status
。
status
条件是word(provided by client)=name2
例如,
[
{
name: "aaa1",
status: True, // if "aaa1" in AA has the word
},
{
name: "aaa2",
status: False, // if "aaa2" in AA doesn't have the word
}
]
所以我在views.py中编写了如下代码,
queryset = (AA.objects.prefetch_related("BB").annotate(
status=Case(
When(BB__name2=word, then=Value(True)),
default=Value(False),
output_field=BooleanField()
)
))
但是结果如下。 (如果单词是“bbb1”)
[
{
name: "aaa1",
status: True, // "bbb1" whose parent is "aaa1"
},
{
name: "aaa1",
status: False, // "bbb2" whose parent is "aaa1"
},
{
name: "aaa1",
status: False, // "bbb3" whose parent is "aaa1"
},
{
name: "aaa2",
status: True, // "bbb1" whose parent is "aaa2"
}
]
我想知道从父母(AA)的角度来看,是否有一个子模型(BB)具有
name2
,并且它返回了所有子模型的列表。
我该怎么办?
用注释中的
Exists
和 OuterRef
解决。
queryset = (AA.objects.prefetch_related("BB").annotate(
status=Exists(
BB.objects.filter(parent=OuterRef("id"), name2=word)
)
))