Created
December 21, 2017 02:24
-
-
Save ninapavlich/e6e90fa25c3882fe83942ddf871302ac to your computer and use it in GitHub Desktop.
Cache foreign key lookups in django admin line forms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this!