gpt4 book ai didi

django - 如何在 select_related 模型上进行注释?

转载 作者:行者123 更新时间:2023-12-04 12:25:34 26 4
gpt4 key购买 nike

我为查询集中的每个对象选择了一个相关对象。如何为每个值注释计算值?

模型:

class School(models.Model):
name = models.CharField(max_length=255)


class Teacher(models.Model):
name = models.CharField(max_length=255)
school = models.ForeignKey(School)


class Student(Entity):
name = models.CharField(max_length=255)
school = models.ForeignKey(School)

我想找到所有老师和他们的学校,以及那所学校的学生人数。

这是我尝试过的:

teachers = Teacher.objects.select_related('school').annotate(student_count=Count('school__student'))

但我可以看出这是错误的,因为学生人数需要按学校计算。

我希望之后能够用我的查询集做这样的事情:

for teacher in teachers:
print(teacher.name, teacher.school.name, teacher.school.student_count)

最佳答案

But I can see that this is wrong as the student count needs to be per school.



好吧,您将计算属于该老师所属学校的学生,因此这在语义上是有效的。但是,注释将放在查询集中的对象上,因此是老师,因此您可以通过以下方式获取学生人数:
for teacher in teachers:
print(teacher.name, teacher.school.name, teacher.student_count)

由于多个老师可以属于同一所学校,因此以这种方式进行注释可能是最好的主意,因为如果不进行优化,这意味着您将为每个老师计算该学校的学生人数。尽管在语义上不会改变任何内容,但查询可能需要相当长的时间。

您可以决定使用 .prefetch_related(..)对于给定的 school ,并在 Prefetch object [Django-doc] 中注释该查询集,这将导致额外的查询,但成本较低。例如:
from django.db.models import Prefetch, Count

teachers = Teacher.objects.prefetch_related(
Prefetch(
'school',
queryset=School.objects.annotate(student_count=Count('student'))
)
)

然后你确实可以查询:
for teacher in teachers:
print(teacher.name, teacher.school.name, teacher.school.student_count)

关于django - 如何在 select_related 模型上进行注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55984912/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com