您可以通过调用add
. Production
问题是您正在保存,而Gallery
不是您已覆盖的 。您需要在结束时致电:Production
save
super(...).save(...)
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)
此外,由于您在这里处理两个模型,因此您应该为此使用 Django 的信号,可能是post-save,它也会为您提供created
标志:
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)
尽管这仍然不能满足您的要求;如果您真的想将默认值Gallery
与每个 new相关联Production
,即使您没有创建默认值,您也会想要这样做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)