[Solved]-Why does Django admin list_select_related not work in this case?

18👍

The issue here is that setting list_select_related = True just adds a basic select_related() onto the query, but that call does not by default follow ForeignKeys with null=True. So the answer is to define the queryset the changelist uses yourself, and specify the FK to follow:

class EventAdmin(admin.ModelAdmin):
    list_display = ('__str__', 'device')
    def queryset(self, request):
        return super(EventAdmin, self).queryset(request).select_related('device')

10👍

Since Django 1.6, list_select_related accepts a boolean, list or tuple with the names of the fields to include in the select_related() call.
Hence you can now use:

class EventAdmin(admin.ModelAdmin):
    list_display = ('__str__', 'device')
    list_select_related = ['device']
👤Fush

0👍

Although select_related is generally the way to go, there are time when one requires more control, then overiding the get_queryset becomes more applicable, this is a more modern version of Daniel Roseman’s answer:

Where foo and bar are foreign key fields:

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.select_related('foo', 'foo__bar').only('foo__field1', 'foo__bar__field2')

Leave a comment