django注释是否存在

use*_*014 11 python sql django

我有一个正在使用的查询:

people = Person.objects.all().annotate(num_pets=Count('pets'))
for p in people:
    print(p.name, p.num_pets == 0)

Run Code Online (Sandbox Code Playgroud)

(宠物与人是多对一的)

但其实我对宠物的数量并不感兴趣,而只对一个人是否养宠物感兴趣。如何才能做到这一点?

Wil*_*sem 19

您可以使用Exists表达式\xc2\xa0 [Django-doc]来确定是否存在PetPerson. 例如:

\n
from django.db.models import Exists, OuterRef\n\nPerson.objects.annotate(\n    has_pet=Exists(Pet.objects.filter(person=OuterRef(\'pk\')))\n)
Run Code Online (Sandbox Code Playgroud)\n

因此,这里的模型Pet有一个ForeignKey名为personto的模型Person。如果字段的名称不同,那么您当然应该相应地更新查询。

\n