Last active
June 8, 2018 04:47
-
-
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.
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
# 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