[Fixed]-Update Django from 1.6 to 1.8: Invalid field name(s) given in select_related

22👍

Django 1.8 checks that the fields given in select_related are correct. The select_related method can be used for foreign keys and one to one fields. It is not possible to use it for the reverse relationship Trace back to TracePoint.

In previous versions of Django, Trace.objects.select_related("trace_points") would not raise an error, but the select_related() call would have no effect.

You can either remove the select_related() call, or replace it with prefetch_related, which will work.

Trace.objects.prefetch_related('trace_points')

7👍

Django’s select_related() doesn’t works for backwards foreignkey relations.

You might want to use prefetch_related() for prefetching all trace points at python level.

models.Trace.objects.prefetch_related("trace_points")
👤v1k45

0👍

With Reverse Foreign Key in one-to-many relationship, select_related() doesn’t work while prefetch_related() works. *This answer explains what is Reverse Foreign Key and this answer explains more about select_related() and prefetch_related().

So, you need to use prefetch_related() instead of select_related() as shown below:

Trace.objects.prefetch_related('trace_points')
# Trace.objects.select_related("trace_points")

Leave a comment