Django带有外键的多个查询 [英] Django multiple queries with foreign keys

查看:114
本文介绍了Django带有外键的多个查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's say I have two different apps :

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)

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

I want to get all the teachers with classes and all classes attached.

我想要的结果:

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

}

这有可能吗?这是我目前正在做的事情:

Is this possible to do? This is what I am currently doing:

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)

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

In the above code, there are four queries made with a loop which certainly increases the time complexity. Is there a better solution to this? Thanks in advance.

推荐答案

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

This will only trigger 2 db queries regardless of how many teachers and classes there are.

这篇关于Django带有外键的多个查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆