|Reported by:||mjtamlyn||Owned by:||nobody|
|Cc:||Triage Stage:||Ready for checkin|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
ModelChoiceField (and MultipleModelChoiceField) take an option cache_choices. This was introduced as a backwards compatibility effort in February 2007 (ee96c7eb2dea86e5bdaf93f7afa91b6f0128dd72) when the fields were made to not always cache their choices (#3534).
The option is undocumented, untested and unused within Django.
There are two possible courses of action here.
Firstly, we could simply remove the option. It should have a deprecation cycle - in particular for people with custom subclasses of ModelChoiceField who pass in the option to the super.
The alternative course of action which I prefer is to harden this into an actual feature. It already works as follows:
- Create the ModelChoiceField with cache_choices=True.
- The ModelChoiceIterator will cache its results on the ModelChoiceField and use that cache.
What would be needed to make this a fully fledged feature in my opinion:
- An API to clear the cache (ModelChoiceField.clear_cache())
- [Very possibly] Plug it in to the cache framework properly
I think this would be a very useful feature, and one which I have had use cases for often. The most obvious use cases is when working with the same form multiple times on a page (either as part of a formset or not) the same query is run for every form. I can call MyForm.fields['modelchoicefield'].clear_cache() after all the forms are rendered.
The biggest possible issue here is that the iterator is not used until the form is rendered. We may need to change when the iterator is evaluated for this case.
I may be able to provide a patch if the feature is accepted.
Change History (6)
comment:1 Changed 20 months ago by mjtamlyn
- Triage Stage changed from Unreviewed to Accepted
- Type changed from New feature to Cleanup/optimization
comment:3 Changed 20 months ago by timo
- Summary changed from ModelChoiceField.cache_choices to Deprecate ModelChoiceField.cache_choices
- Triage Stage changed from Accepted to Ready for checkin