Django使用外键进行多个查询

时间:2018-10-10 06:44:52

标签: 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)

我想让所有上课的老师和所有上课的老师

我想要的结果

{[
   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)

在上面的代码中,使用循环进行了四个查询,这肯定会增加时间复杂度。有更好的解决方案吗?预先感谢。

1 个答案:

答案 0 :(得分:0)

使用prefetch_related

const layers = ["layer1", "layer2", "layer3"];

async function connect(layer: string): Promise<object> {
    return new Promise((resolve, reject) => {
        setTimeout(function () {
            resolve(layer);
        }, 1000);
    });
}

await Promise.all(layers.map(connect));
console.log('All layers are connected');

这将仅触发2个数据库查询,而不管有多少老师和班级。