我有一个表Parent,一个表Child具有一个指向表Parent的外键。
我想对所有父项以及名称为'Eric'的那些子项记录进行查询。
我跑步:
parents = Parents.objects.filter(child__name='Eric')
然后我遍历查询集:
for parent in parents:
print(f'Parent name {parent.name} child Eric age {parent.child.age}')
显然这不起作用-我需要通过外键对象管理器访问子对象,所以我尝试:
for parent in parents:
print(f'Parent name {parent.name}')
for child in parent.child_set.all():
print(f'Child Eric age {parent.child.age}')
Django返回所有孩子的年龄,而不仅仅是名叫Eric的孩子。
我可以重复过滤条件:
parents = Parents.objects.filter(child__name='Eric')
for parent in parents:
print(f'Parent name {parent.name}')
for child in parent.child_set.filter(name='Eric'):
print(f'Child Eric age {child.age}')
但是这意味着重复的代码(因此当另一个开发人员对另一个进行更改时,可能会出现将来的不一致风险,并在数据库上运行第二个查询。
您可以用Eric
年龄注释父母:
from django.db.models import F
parents = Parents.objects.filter(child__name='Eric').annotate(
child_age=F('child__age')
)
for parent in parents:
print(f'{parent.name}: {parent.child_age}')
这还将获取同一查询中子代的年龄,因此效率更高,因为通常Web服务器延迟的主要因素之一是查询的[[number。