I seem to recall a similar problem rears it's ugly head on editable changelists too.
And obviously it's potentially worse there as n can often be larger. On May 23, 4:29 pm, Sean Brant <brant.s...@gmail.com> wrote: > If you have ever used a inline in the admin for a model that contained > a model choice field you have probably noticed it has to query the > database for each row to fill the select drop-down. This results in n+ > identical queries. > > I though it might be useful to have a way to tell a admin inline to > cache the choices of fields. Here is some rough code that gets the job > done:: > > from django.forms.models import BaseInlineFormSet > > class CachedInlineFormSet(BaseInlineFormSet): > cached_fields = [] > > def _construct_form(self, i, **kwargs): > form = super(CachedInlineFormSet, self)._construct_form(i, > **kwargs) > for cache_field in self.cached_fields: > field = form.fields[cache_field] > field.cache_choices = True > choices = getattr(self, '_cached_%s_choices' % > cache_field, None) > if choices is None: > choices = list(field.choices) > setattr(self, '_cached_%s_choices' % cache_field, > choices) > field.choice_cache = choices > return form > > class CachedTabularInline(admin.TabularInline): > cached_fields = [] > > def get_formset(self, request, obj=None, **kwargs): > formset = super(CachedTabularInline, > self).get_formset(request, obj=None, **kwargs) > formset.cached_fields = self.cached_fields > return formset > > class MyInline(CachedTabularInline): > model = MyModel > cache_fields = ['myfk'] > > Im not super big on how this patches the classes in various places so > i'm open to better suggestions. Is this something that the admin could > benefit from or is this better kept as a 3rd party tool? -- You received this message because you are subscribed to the Google Groups "Django developers" group. To post to this group, send email to django-developers@googlegroups.com. To unsubscribe from this group, send email to django-developers+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-developers?hl=en.