attempt at ModelChoiceField queryset caching
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
# 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