gpt4 book ai didi

python - Django 使用外键进行多个查询

转载 作者:行者123 更新时间:2023-11-29 16:52:52 31 4
gpt4 key购买 nike

假设我有两个不同的应用程序:

teacher/models.py:

Teacher(models.Model):
name = models.CharField(max_length=300)


class/models.py:

Class(models.Model):
name = models.CharField(max_length=300)
teacher = models.ForeignKey(Teacher)
students = models.ManyToManyField(Student)

我想要所有有类(class)的老师和所有附加的类(class)。

我想要的结果:

{[
teacher: '3L' #Teachers Id
classes: ['20L','14L','30L'] #list of Class objects or ids with the above teacher
],
[# similar to above]

}

这可以做到吗?这就是我目前正在做的事情:

classes = Class.objects.all()
teachers = Teacher.objects.filter(id__in=classes.value_list('teacher',flat=True).distinct())
for teacher in teachers:
classes_for_teachers = classes.objects.filter(teacher=teacher)

在上面的代码中,有四个循环查询,这无疑增加了时间复杂度。对此有更好的解决方案吗?提前致谢。

最佳答案

使用prefetch_related :

teachers = Teacher.objects.prefetch_related('class_set')

# what you want is not a valid Python structure (set of lists (looking like dicts))
# list of dicts makes more sense
result = [
{'teacher': t.pk, 'classes': t.class_set.all()}
for t in teachers
]

无论有多少教师和类(class),这都只会触发 2 个数据库查询。

关于python - Django 使用外键进行多个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52734174/

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