Skip to content

Instantly share code, notes, and snippets.

@ninapavlich
Created December 21, 2017 02:24
Show Gist options
  • Select an option

  • Save ninapavlich/e6e90fa25c3882fe83942ddf871302ac to your computer and use it in GitHub Desktop.

Select an option

Save ninapavlich/e6e90fa25c3882fe83942ddf871302ac to your computer and use it in GitHub Desktop.
Cache foreign key lookups in django admin line forms
class CachedChoiceFieldOptionsMixin(object):
"""
This class speeds up performance of inline foreign-key pickers so we don't have to re-query the options for each item in the list
"""
cached_choice_fields = []
def formfield_for_dbfield(self, db_field, **kwargs):
request = kwargs['request']
formfield = super(CachedChoiceFieldOptionsMixin,
self).formfield_for_dbfield(db_field, **kwargs)
if db_field.name in self.cached_choice_fields:
cache_key = self.get_cache_key(db_field.name)
choices = getattr(request, cache_key, None)
if choices is None:
choices = list(formfield.choices)
setattr(request, cache_key, choices)
formfield.choices = choices
return formfield
def get_cache_key(self, db_field_name):
return u'_%s_%s_choices_cache' % (self.model._meta.db_table, db_field_name)
class MyModelInline(CachedChoiceFieldOptionsMixin, admin.TabularInline):
extra = 0
model = MyModel
fields = ['alpha', 'beta']
cached_choice_fields = ['alpha']
@dgrant
Copy link
Copy Markdown

dgrant commented Jan 28, 2019

Thank you for this!

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