我使用Django,我有两个模型:
class Source(models.Model):
def __str__(self):
return "Test"
class SecurityGroup(models.Model)
name = models.CharField(max_length=20)
source = models.ForeignKey(Source)
我希望当我添加一个新的SecurityGroup时,会自动附加一个带有他ID的新Source,而这个ID将是SecurityGroup中的源阵营。
我一直在寻找,我发现覆盖方法save(),但我不知道该怎么办..
谢谢!
答案 0 :(得分:2)
了解signals。
post_save
版本:
from django.db.models.signals import post_save
from django.dispatch.dispatcher import receiver
@receiver(post_save, sender=SecurityGroup)
def add_source(sender, instance, created, **kwargs):
if created:
source = Source()
source.save()
instance.source = source
instance.save()
pre_save
版本:
from django.db.models.signals import pre_save
from django.dispatch.dispatcher import receiver
@receiver(pre_save, sender=SecurityGroup)
def add_source(sender, instance, **kwargs):
if instance.source is None:
source = Source()
source.save()
instance.source = source
答案 1 :(得分:2)
正如您所提到的,您可以覆盖SecurityGroup
的保存方法并在那里创建一个新的Source
对象:
class SecurityGroup(models.Model)
name = models.CharField(max_length=20)
source = models.ForeignKey(Source)
def save(self, *args, **kwargs):
if self.source is None:
self.source = Source.objects.create()
super(SecurityGroup, self).save(*args, **kwargs)