Opened 4 years ago

Closed 4 years ago

#18361 closed Cleanup/optimization (wontfix)

Accessing a ModelChoiceField property in a template triggers QuerySet evaluation

Reported by: Kevin Michel 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 Kevin Michel 4 years ago.

Download all attachments as: .zip

Change History (3)

Changed 4 years ago by Kevin Michel

Attachment: form_widget_iteration.diff added

comment:1 Changed 4 years ago by Natim87

Needs documentation: unset
Needs tests: unset
Patch needs improvement: unset
Triage Stage: UnreviewedDesign decision needed

comment:2 Changed 4 years ago by Jacob

Resolution: wontfix
Status: newclosed

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