我有一个django模型如下:
class M1(models.Model):
m1code = models.CharField(max_length=25)
m1title = models.CharField(max_length=500)
m1description = models.CharField(max_length=1000, null=True, blank=True)
def __unicode__(self):
return self.m1title
class M2(models.Model):
m1 = models.ForeignKey(M1)
m2code = models.CharField(max_length=25)
m2title = models.CharField(max_length=500)
m21description = models.CharField(max_length=1000, null=True, blank=True)
def __unicode__(self):
return self.m2title
这里我有两个型号,一个型号M2有M1的外键。每当我从shell进入M1时,我希望django自动输入值甚至进入M2,M2中的外键m1自动指向M1中的条目。我将如何实现这一目标?
答案 0 :(得分:1)
您可以通过overriding the predefined model method save()
:
class M1(models.Model):
...
def save(self, *args, **kwargs):
super(M1, self).save(*args, **kwargs) # Call the "real" save() method.
m2 = M2(m1=self, m2code=self.m1code, m2title=self.m1title, m2description=self.m1description)
m2.save()