django-admin: creating,saving and relating a m2m model

Posted by pastylegs on Stack Overflow See other posts from Stack Overflow or by pastylegs
Published on 2010-11-14T14:48:00Z Indexed on 2010/12/23 1:54 UTC
Read the original article Hit count: 670

I have two models:

class Production(models.Model):
    gallery = models.ManyToManyField(Gallery)

class Gallery(models.Model):
    name = models.CharField()

I have the m2m relationship in my productions admin, but I want that functionality that when I create a new Production, a default gallery is created and the relationship is registered between the two.

So far I can create the default gallery by overwriting the productions save:

def save(self, force_insert=False, force_update=False):
    if not ( Gallery.objects.filter(name__exact="foo").exists() ):
        g = Gallery(name="foo")
        g.save()
        self.gallery.add(g)

This creates and saves the model instance (if it doesn't already exist), but I don't know how to register the relationship between the two?

© Stack Overflow or respective owner

Related posts about django

Related posts about django-models