Opened 4 years ago

Closed 3 years ago

#18361 closed Cleanup/optimization (wontfix)

Accessing a ModelChoiceField property in a template triggers QuerySet evaluation

Reported by: kmichel_wgs Owned by: nobody
Component: Forms Version: 1.4
Severity: Normal Keywords:
Cc: Triage Stage: Design decision needed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


When reading a property of a ModelChoiceField in a template :
{{ form.something.label }}
The template languages first tries to evaluate form.something['label'].

Since ModelChoiceFields are iterable, the __getitem__ implementation
calls __iter__, which, if the field is bound to a QuerySet, force its evaluation.

A simple type check before building the list in __getitem__ can avoid this inefficiency.

Attachments (1)

form_widget_iteration.diff (494 bytes) - added by kmichel_wgs 4 years ago.

Download all attachments as: .zip

Change History (3)

Changed 4 years ago by kmichel_wgs

comment:1 Changed 4 years ago by Natim87

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Triage Stage changed from Unreviewed to Design decision needed

comment:2 Changed 3 years ago by jacob

  • Resolution set to wontfix
  • Status changed from new to closed

There's never going to be a way to prevent QS evaluation holistically from the template. Ultimately it's code, even if we try to limit it, so here again the answer to "it hurts when I do this" is "stop doing that."

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