Django模型 - 使用QuerySet在M2M场景中自我加入FK

时间:2009-07-19 22:53:34

标签: django-models join count

让我们采取以下M2M方案。

我希望得到所有学生的所有同事,以及他们两人参加的课程数量。 (这意味着给定学生与每位同事和他的同事共有多少门课程。)

class Student(models.Model):
    pass

class Course(models.Model):
    students = models.ManyToManyField(Student, through='Attendance')

class Attendance(models.Model):
    student = models.ForeignKey(Student)
    course = models.ForeignKey(Course)

查询看起来像这样

SELECT 
    S.id AS student_id, 
    A2.student_id AS colleague_id, 
    COUNT(A2.course_id) AS number_of_courses_both_of_them_attend
FROM student S
JOIN attendance A1 
    ON S.id = A1.student_id
JOIN attendance A2 
    ON (A1.course_id = A2.course_id AND A1.student_id != A2.student_id)
GROUP BY 1, 2

我很感激有关如何使用QuerySet方法完成此任务的任何提示。

谢谢!

1 个答案:

答案 0 :(得分:1)

colleagues = Student.objects.filter(course_set__students=your_student).exclude(id=your_student).distinct()

为每位学生添加courses_cnt属性:

colleagues = colleagues.annotate(courses_cnt = Count('attendance_set'))