Django-过滤prefetch_related查询集

时间:2018-10-11 09:46:20

标签: python mysql django python-2.7 prefetch

我正在尝试通过执行以下操作来减少我的复杂性。我试图让所有的老师都在活跃的教室里。

teacher/models.py:

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


classroom/models.py:

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

admin/views.py

teachers = Teacher.objects.prefetch_related(Prefetch('classroom_set',queryset=Classroom.objects.filter(status='Active'))


for teacher in teachers:
    classrooms = teacher.all()
    # run functions

通过这样做,我让老师有了教室。但是它也返回没有我不想要的活动教室(空列表)的老师。因此,我必须在空荡荡的教室里绕着成千上万的老师。我有什么办法可以删除教室设置为[]的那些老师?

这是我最初的问题- Django multiple queries with foreign keys

谢谢

1 个答案:

答案 0 :(得分:1)

如果您希望所有老师都拥有至少一个相关的 active 班级,则无需预取它们,则可以过滤相关的对象,例如:

Teacher.objects.filter(class__status='Active').distinct()

如果您还想过滤classroom_set,则需要结合过滤和.prefetch_related

Teacher.objects.filter(
    class__status='Active'
).prefetch_related(
    Prefetch('class_set', queryset=Class.objects.filter(status='Active'))
).distinct()

在这里,我们将像这样过滤:

SELECT DISTINCT teacher.*
FROM teacher
JOIN class on class.teacher_id = teacher.id
WHERE class.status = 'Active'