Doing a right join in django

Here are my models

class Student:
    user  = ForeignKey(User)
    department = IntegerField()
    semester = IntegerField()
    ...

class Attendance:
    student = ForeignKey(Student)
    subject = ForeignKey(Subject)
    month = IntegerField()
    year = IntergerField()
    present = IntegerField() 
    total = IntegerField()

students = Student.objects.filter(semester=semester)

      

How can I make the correct connection between the models Student

and Attendance

so that I can get a queryset with all students

and attendances `if exists for student, otherwise null?

The documentation mentions left joins, but not correct joins.

+3


source to share


1 answer


You can use a query like this:

queryset = Student.objects.all().select_related('attendance_set')
student = queryset[0]
# all attendances for the student
attendances = student.attendance_set.all() 

      

Since select_related

you're JOIN

'ing Attendance

. Django doesn't have an explicit JOIN

ORM method , but it does internally JOIN

when you call select_related

. The resulting query will contain everything Student

with associated participants, and when you call attencande_set.all()

for each student, there will be no additional queries. Check the docs for the feature_set

.



If you want to query only those students who have at least one attendance, you can use a query like this:

from django.models import Count
(Student.objects.all()
                .select_related('attendance_set')
                .annotate(n_attendances=Count('attendance_set'))
                .filter(n_attendances__gt=0))

      

+1


source







All Articles