Skip to content

Instantly share code, notes, and snippets.

@jnns
Created August 22, 2013 12:24
Show Gist options
  • Save jnns/6306501 to your computer and use it in GitHub Desktop.
Save jnns/6306501 to your computer and use it in GitHub Desktop.
A Mixin to prevent unnecessary queries in Django Formsets. This Mixin can be added to `admin.StackedInline` or `admin.TabularInline` in order to prevent querysets to be evaluated for each and every occurence of a `ModelChoiceField`. Say, you have a ModelAdmin that has currently 25 related objects in an InlineFormSet where each form has 2 Foreign…
class ForeignKeyCacheMixin(object):
"""
Cache foreignkey choices in the request object to prevent unnecessary queries.
"""
def formfield_for_foreignkey(self, db_field, request, **kwargs):
formfield = super(ForeignKeyCacheMixin, self).formfield_for_foreignkey(db_field, **kwargs)
cache = getattr(request, 'db_field_cache', {})
if cache.get(db_field.name):
formfield.choices = cache[db_field.name]
else:
formfield.choices.field.cache_choices = True
formfield.choices.field.choice_cache = [
formfield.choices.choice(obj) for obj in formfield.choices.queryset.all()
]
request.db_field_cache = cache
request.db_field_cache[db_field.name] = formfield.choices
return formfield
@runekaagaard
Copy link

This works beautifully, thx!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment