开发者

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

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(开发者_JS百科)
        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?


You register the relationship just as you have, by calling add on the Production. The problem is that you're saving the Gallery, but not the Production whose save you've overridden. You need to call super(...).save(...) at the end of your 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)
    super(Production, self).save(force_insert=force_insert, force_update=force_update)

Furthermore, since you're dealing with two models here, you should use Django's signals for this, probably post-save, which will also give you the created flag:

def create_default_gallery(sender, instance, created, **kwargs):
    if created and not Gallery.objects.filter(name__exact="foo").exists():
        g = Gallery(name="foo")
        g.save()
        instance.gallery.add(g)
models.signals.post_save.connect(create_default_gallery, sender=Production)

Though this still won't do what you say you want; if you really want to associate the default Gallery with every new Production, you'll want to do it even when you're not creating the default Gallery:

def create_default_gallery(sender, instance, created, **kwargs):
    if created:
        g = Gallery.objects.get_or_create(name__exact="foo")
        g.save()
        instance.gallery.add(g)
models.signals.post_save.connect(create_default_gallery, sender=Production)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜