Opened 11 years ago

Closed 11 years ago

Last modified 9 years ago

#10742 closed (duplicate)

ModelAdmin.list_select_related needs three-valued logic to support custom select_related() calls

Reported by: mrts Owned by: nobody
Component: contrib.admin Version: master
Severity: Keywords: efficient-admin
Cc: Triage Stage: Unreviewed
Has patch: yes Needs documentation: yes
Needs tests: yes Patch needs improvement: yes
Easy pickings: no UI/UX: no


If any of the related fields in a model is nullable, e.g.

class C(Base):
    a = models.ForeignKey(A, blank=True, null=True)
    b = models.ForeignKey(B)
    is_published = models.BooleanField()

, select_related() does not pull them in by default (see

Forcing it explicitly as follows

class CAdmin(admin.ModelAdmin):
    list_display = ('name', 'a', 'b', 'is_published')
    list_select_related = None

    def queryset(self, request):
        qs = super(CAdmin, self).queryset(request)
        return qs.select_related('a', 'b')

has no effect, as ChangeList.get_query_set() blindly overrides it with a plain select_related() (see [source:django/trunk/django/contrib/admin/views/]).

To get the desired behviour of pulling in the nullable relations in a single query, three-valued logic is required for ModelAdmin.list_select_related:

  • True -- always call select_related(),
  • False (the default) -- call select_related() if any of the fields in list_display is a foreign key,
  • None (added) -- leave the queryset alone.

Patch attached.

See also #10722 and .

Attachments (1)

10742_three-valued-list_select_related.diff (1.6 KB) - added by mrts 11 years ago.

Download all attachments as: .zip

Change History (4)

comment:1 Changed 11 years ago by mrts

Keywords: efficient-admin added
Needs documentation: set
Needs tests: set
Patch needs improvement: set

(I'll write proper tests and docs if this is accepted.)

comment:2 Changed 11 years ago by Jacob

Resolution: duplicate
Status: newclosed

Duplicate of #10348

comment:3 Changed 9 years ago by Jacob

milestone: 1.1

Milestone 1.1 deleted

Note: See TracTickets for help on using tickets.
Back to Top