Django - 过滤 prefetch_related 查询集

Django - Filter the prefetch_related queryset

我正在尝试通过执行以下操作来降低我的复杂性。我正在努力让所有的老师都在活跃的课堂上。

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

通过这样做,我得到了带教室的老师。但它也 returns 没有活跃教室(空列表)的老师,这是我不想要的。正因为如此,我不得不绕着空classroom_set的数千名老师转了一圈。有什么方法可以删除那些 classroom_set 是 [ ] 的老师吗?

这是我原来的问题 -

谢谢

如果你想要所有教师至少有一个相关的 active class,你不需要预取这些,你可以过滤相关的对象,比如:

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

如果你想过滤classroom_set,你需要结合过滤和.prefetch_related:

from django.db.models import Prefetch

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'