#22841: ModelChoiceField does not make it easy to reuse querysets
-----------------------------+------------------------------------
Reporter: Marc Tamlyn | Owner: (none)
Type: New feature | Status: closed
Component: Forms | Version: master
Severity: Normal | Resolution: wontfix
Keywords: | Triage Stage: Accepted
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-----------------------------+------------------------------------
Changes (by Carlton Gibson):
* status: new => closed
* resolution: => wontfix
Comment:
I gave a talk on this exact topic for DjangoCon Europe 2020. It's only 20
minutes. I show examples for a DRF serializer form, a regular form with
django-filter and a FormSet via the admin using `list_editable`
The video is here: [https://www.youtube.com/watch?v=e52S1SjuUeM Choose and
Choose Quickly: Optimizing ModelChoiceField]
* We can't drop the `all()` calls, since they're explicitly there to avoid
reusing cached data. (From the talk: ''"There's only one thing worse that
slow data, and that's wrong data."'')
* I don't think an additional `evaluated_queryset` attribute is necessary
because (at any place you have that code in hand) setting `choices`
directly is no more work (certainly not enough to merit extra API)
* Setting `choices` is exactly the intended API here. There's not an exact
optimization pattern documented but, `choices` has been ≈forever, and
`ModelChoiceIterator` has been documented since
5da85ea73724d75e609c5ee4316e7e5be8f17810.
TBH I don't think one needs to bring `ModelChoiceIterator` into play. The
example I use in the talk is just:
{{{
author_choices =
list(forms.ModelChoiceField(Author.objects.all()).choices)
}}}
Because I'm doing this outside of the form context, in order to provide to
the form later:
{{{
self.fields["author"].choices = author_choices
}}}
The example in the description, purely inside `BookForm.__init__()` could
well just be:
{{{
self.fields['category'].choices = list(self.fields['category'].choices)
}}}
You evaluate once, setting the output for reuse later.
--
Ticket URL: <https://code.djangoproject.com/ticket/22841#comment:10>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/066.2fc4a93964089c28c2f64d7e54023531%40djangoproject.com.