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

标签 python mysql django prefetch

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

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/

相关文章:

python - 数字化 numpy 数组

python - 如何在 Django Rest Framework 中重命名外键集字段

Django 查询集操作

python - 具有 AJAX 行为的 Django 分页

python - 在 Bokeh 刻度标签中插入换行符

Python:在函数的本地命名空间中包含字典的条目

python - Pygame菜单: calling another . py文件

html - 如何在 textarea 中显示实际的 HTML 代码而不是呈现的 HTML?

mysql - 在 SQL 结果中创建一个新列

mysql - 聚合函数有