3

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?

Derek
  • 197
  • 2
  • 11

1 Answers1

3

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.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895