Opened 10 years ago

Closed 9 years ago

#23710 closed Bug (needsinfo)

ModelForm is not using the plain manager for foreign keys

Reported by: eagle-r Owned by: nobody
Component: Database layer (models, ORM) Version: 1.7
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

According to the documentation, Django will use an instance of the plain manager instead of the default manager for related fields (see https://docs.djangoproject.com/en/1.7/topics/db/managers/#using-managers-for-related-object-access).

However, the ModelForm initialisation code is using the default manager instead when initialising the fields during loading (see django/db/models/fields/related.py:1749)

So, if you have a model that is using a custom default manager, the modelform attempts to use this manager instead leading to some very unexpected side effects particularly when running the server and loading up the code initially.

Change History (3)

comment:1 by Collin Anderson, 10 years ago

The default manager is the first manager defined, not necessarily a "plain" manager, right?
https://github.com/django/django/blob/d49183e4bed8ecf21faad44372ea15ff00f781b5/django/db/models/manager.py#L127-129

comment:2 by Tim Graham, 10 years ago

Component: UncategorizedDatabase layer (models, ORM)

Collin, yes that's what's documented in the default managers docs.

I am not sure about this. The behavior doesn't seem to be well defined as I couldn't find any documentation about this and no tests fail if I make this change (please correct me if this is the wrong line; this is the closest line I could find on stable/1.7.x to the one you referenced):

  • django/db/models/fields/related.py

    diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py
    index d87a922..0b4d726 100644
    a b class ForeignKey(ForeignObject):  
    17591759                             (self.name, self.rel.to))
    17601760        defaults = {
    17611761            'form_class': forms.ModelChoiceField,
    1762             'queryset': self.rel.to._default_manager.using(db),
     1762            'queryset': self.rel.to._base_manager.using(db),
    17631763            'to_field_name': self.rel.field_name,
    17641764        }
    17651765        defaults.update(kwargs)

On the other hand, I could see the current behavior as expected and changing it could cause problems for people relying on it.

comment:3 by Tim Graham, 9 years ago

Resolution: needsinfo
Status: newclosed

Lacking any follow-up from the reporter, I'm going to close as "needs info". Feel free to reopen if you can describe more about the problem here.

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