Skip to content

Instantly share code, notes, and snippets.

@pawl
Created Apr 23, 2020
Embed
What would you like to do?
attempt at ModelChoiceField queryset caching
# See full example: https://github.com/pawl/django_modelchoicefield_caching/blob/master/myapp/views.py#L31-L51
for song in playlist:
form_data = {'title': song["title"], 'artist': song["artist"]}
song_form = forms.SongFormWithModelChoiceField(data=form_data)
song_form.is_valid() # runs a query to get the ModelChoiceField queryset each time
print('ModelChoiceField - query count AFTER validating all songs:',
len(connection.queries)) # 5 queries
# query for choices outside of the loop to prevent unnecessary queries
artist_choices = [(artist.pk, artist.name)
for artist in models.Artist.objects.all()]
for song in playlist:
form_data = {'title': song["title"], 'artist': song["artist"]}
# pass choices into the Form
song_form = forms.SongFormWithChoiceField(
artist_choices=artist_choices,
data=form_data)
song_form.is_valid()
print('ChoiceField w/ choices passed in - query count AFTER validating all songs:',
len(connection.queries)) # 6 queries (only 1 more query!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment