Created
August 22, 2013 12:24
-
-
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…
This file contains hidden or 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 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 |
This works beautifully, thx!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm new to using Django, but this is exactly what I need to do. Can you explain how to use it in the 'admin.TabularInline'? Do I just need to do something like:
class LabelInline(ForeignKeyCacheMixin, admin.TabularInline):