Reputation: 4421
models.py
class Playlist(models.Model):
name = models.CharField(max_length=50)
num_of_songs = models.IntegerField(max_length=15)
duration = models.IntegerField()
owner = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
songs = models.ManyToManyField("Song", blank=True)
forms.py
class PlaylistEditForm(forms.ModelForm):
class Meta:
model = Playlist
fields = ['name', 'songs']
I calculate duration
and num_of_songs
based on the songs I get from the form. But I do that calculation from a view.
views.py
playlist = Playlist.objects.get(id=playlist_id)
if request.method == 'POST':
form = PlaylistEditForm(request.POST, instance=playlist)
if form.is_valid():
form.save()
playlist.duration = playlist.songs.aggregate(Sum('duration'))['duration__sum'] or 0
playlist.num_of_songs = playlist.songs.count()
playlist.save()
I want to calculate duration
and num_of_songs
inside a form.
Upvotes: 0
Views: 2295
Reputation: 627
Is there any reason not to do it in the models save()
method? If you have it in the forms save() method, the duration and num_of_songs in the database will not get updated if you save the model instance other than from the modelform.
class Playlist(models.Model):
name = models.CharField(max_length=50)
num_of_songs = models.IntegerField(max_length=15)
duration = models.IntegerField()
owner = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
songs = models.ManyToManyField("Song", blank=True)
def save(self, *args, **kwargs):
if self.pk:
self.duration = self.songs.aggregate(Sum('duration'))['duration__sum'] or 0
self.num_of_songs = self.songs.count()
return super(Playlist, self).save(*args, **kwargs)
You view would be:
if request.method == 'POST':
form = PlaylistEditForm(request.POST, instance=playlist)
if form.is_valid():
playlist = form.save()
Upvotes: 0
Reputation: 11596
you can move the calculation to the form overriding the form's save
method
def save(self, commit=True):
instance = super(PlaylistEditForm, self).save(commit=False)
instance.duration = instance.songs.aggregate(Sum('duration'))['duration__sum'] or 0
instance.num_of_songs = instance.songs.count()
if commit:
instance.save()
return instance
and your view becomes
playlist = Playlist.objects.get(id=playlist_id)
if request.method == 'POST':
form = PlaylistEditForm(request.POST, instance=playlist)
if form.is_valid():
form.save()
Please refer to Django's official docs for further info.
Upvotes: 2