Saša Kalaba
Saša Kalaba

Reputation: 4421

Can you access ManyToManyField values before saving in Django 1.7?

class Playlist(models.Model):
    name = models.CharField(max_length=50)
    num_of_songs = models.IntegerField(max_length=15)
    duration = models.IntegerField()
    songs = models.ManyToManyField("Song", blank=True)

    def save(self, *args, **kwargs):
        self.num_of_songs = self.songs.count() ==> this is wrong, but you get the idea
        super(Playlist, self).save(*args, **kwargs)

NOTE: The save method above is not a part of the original code, I added this to show you what I'm going for.

I have a Playlist model in Django as described above. When I create a playlist from my views, I use a ModelForm to save the object. In other words i do a form.save(), and then append the correct num_of_songs and duration based on the songs that are saved in the database, and then i do a playlist.save().

That all works fine and dandy, but if I create a playlist from django admin however, I have to manually enter those values, and they won't be changed unless I change the list from the view. So in admin I can enter wrong values and they'll stay that way.

When I try to override the save method, I can't get the selected songs because they're not saved in the database yet.

So my question is, is there a way to read the selected values from ManyToManyField before save? (I guess I could use a form, but working from admin I'm not sure if that's possible.)

Upvotes: 1

Views: 1452

Answers (1)

Danial Tz
Danial Tz

Reputation: 1984

As you will see save_model override to modelAdmin will also not work since django resets the manytomany on save.

Check: http://reinout.vanrees.org/weblog/2011/11/29/many-to-many-field-save-method.html

Upvotes: 2

Related Questions