Opened 3 years ago

Closed 3 years ago

Last modified 3 years ago

#21405 closed Bug (fixed)

Regression in ability to override queryset on BaseModelAdmin.formfield_for_foreignkey

Reported by: guido@… Owned by: Claude Paroz
Component: contrib.admin Version: 1.6
Severity: Release blocker Keywords:
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

After upgrading to Django 1.6, i have a problem with formfield_for_foreignkey.

This is my code:

class MatchScoreIntInline(admin.TabularInline):
    model = MatchScoreInt

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "partial":
            kwargs["queryset"] = Partial.objects.filter(...my filters...)
        if db_field.name == "subscriber":
            kwargs["queryset"] = Subscriber.objects.filter(...my filters...)
        return super(MatchScoreIntInline, self).formfield_for_foreignkey(db_field, request, **kwargs)

The super method override my kwargsqueryset?, only for "subscriber" db_field because of this code:

queryset = self.get_field_queryset(db, db_field, request)
        if queryset is not None:
            kwargs['queryset'] = queryset

get_field_queryset method return a new ordered queryset if the related admin has "ordering" parameter.
So I removed the ordering parameter from my ModelAdmin and everything works fine.

Why I cannot override the queryset with formfield_for_foreignkey method when the related_admin has "ordering" parameter set?

Change History (4)

comment:1 Changed 3 years ago by Tim Graham

Component: Uncategorizedcontrib.admin
Needs documentation: unset
Needs tests: unset
Patch needs improvement: unset
Severity: NormalRelease blocker
Summary: formfield_for_foreignkeyRegression in ability to override queryset on BaseModelAdmin.formfield_for_foreignkey
Triage Stage: UnreviewedAccepted
Type: UncategorizedBug

This regression was introduced in [d9330d5b]. It looks like the solution would be to avoid calling get_field_queryset() if 'queryset' in kwargs. This fix probably also applies to formfield_for_manytomany().

The code from the second block in the ticket description is from django/contrib/admin/options.py.

comment:2 Changed 3 years ago by Claude Paroz

Owner: changed from nobody to Claude Paroz
Status: newassigned

comment:3 Changed 3 years ago by Claude Paroz <claude@…>

Resolution: fixed
Status: assignedclosed

In 1718b5256cd65b8701e315e307c2eb2b5dd4c8d9:

Fixed #21405 -- Prevented queryset overwrite in BaseModelAdmin

Thanks guido@… for the report and Tim Graham for the
analyze.

comment:4 Changed 3 years ago by Claude Paroz <claude@…>

In 9cbcd06b1adf5a505646f30898c3370d1c4ab726:

[1.6.x] Fixed #21405 -- Prevented queryset overwrite in BaseModelAdmin

Thanks guido@… for the report and Tim Graham for the
analyze.
Backport of 1718b5256c from master.

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