[Django]-How can I make Django use select_related() on a foreign key in the admin site?

2👍

You need to inject the select_related at the time that the admin site creates the change form. You can do this by overriding ModelAdmin.formfield_for_foreignkey for your ModelAdmin. Something like this:

class ReviewAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "record":
            kwargs["queryset"] = Record.objects.all().select_related()

        return super(ReviewAdmin, self).formfield_for_foreignkey(
            db_field, request, **kwargs)

1👍

Given your comment you may actually need to select related both the record and its band. Like this:

class ReviewAdmin(admin.ModelAdmin):
    model = Review
    def queryset(self, request):
        return super(ReviewAdmin, self).queryset(request).select_related('record', 'record__band')

class RecordAdmin(admin.ModelAdmin):
    model = Record
    def queryset(self, request):
        return super(RecordAdmin, self).queryset(request).select_related('band')

Using the Django Toolbar is a good way to discover what queries are being run.

Leave a comment