Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ranelpadon/acc89424afd4008808373635fef15a14 to your computer and use it in GitHub Desktop.
Save ranelpadon/acc89424afd4008808373635fef15a14 to your computer and use it in GitHub Desktop.
Custom Django model.save() kwarg to avoid executing costly codes if there are lots of formsets in the page.
# forms.py
class EventSessionFormSet();
...
def save(self, commit=True):
sessions = []
forms = self.forms
total_forms = len(forms)
for i, form in enumerate(forms):
update_event_fields = False
# Trigger the save kwargs only if form is the last in formset
# because the kwarg is used to avoid executing a custom block in EventSession.save()
# every time a form is saved (performance optimization).
if i == total_forms - 1:
update_event_fields = True
# form.save() and model.save() combo to pass a custom kwarg.
session = form.save(commit=False)
session.save(update_event_fields=update_event_fields)
sessions.append(session)
# Need to return the saved instances.
return sessions
# models.py
class EventSession():
event = models.ForeignKey(Event, related_name='sessions')
...
def save(self, *args, **kwargs):
update_event_fields = False
# Remove the custom kwarg before calling super() to prevent error.
if kwargs.has_key('update_event_fields'):
update_event_fields = kwargs.pop('update_event_fields')
super(EventSession, self).save(*args, **kwargs)
if update_event_fields and self.event.has_multi_sessions:
sessions = self.event.sessions
if sessions.exists():
self.event.session_earliest_starts = sessions.order_by('starts').first().starts
self.event.session_latest_ends = sessions.order_by('ends').last().ends
self.event.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment