Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing a right join in django (take 2)

With reference to Performing a right join in django , when I try a similar approach (field slightly different):

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

class Attendance:
    student_attending = ForeignKey(Student, related_name='attendee')
    subject = ForeignKey(Subject)

When I run this query:

queryset = Student.objects.all().select_related('attendance_set')

I get this response:

django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'attendance_set'. 

What could trigger that warning and how do I get the 'join' to work properly?

like image 690
Derek Avatar asked Nov 19 '25 01:11

Derek


1 Answers

The accepted answer to that linked question is, quite simply, wrong - as a comment there notes.

select_related only works for forward relationships. For backwards ones, you need prefetch_related:

Student.objects.all().prefetch_related('attendance_set')

Note, this will do two separate queries.

like image 107
Daniel Roseman Avatar answered Nov 20 '25 18:11

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!