2014-12-05 106 views
1

说我有以下的模型Django的:如何将一个字段的默认值设置为一个字段的值在父模型

class Sammich(models.Model): 
    name = models.CharField(max_length=200) 
    ratio_of_cheese_to_meat = models.FloatField(default=0.3) 

我希望能够创建一个具有领域的新典范这从Sammich类的ratio_of_cheese_to_meat中提取默认值

class DeliSammich(models.Model): 
    sammich = models.ForiegnKey(Sammich) 
    type_of_meat = models.CharField(max_length=200) 
    type_of_cheese = models.CharField(max_length=200) 
    ratio_of_cheese_to_meat = models.FloatField(default=Sammich.objects.get(pk=sammich.id).ratio_of_cheese_to_meat) 

哪一个不起作用。

回答

0

你可以使用全局变量来解决这个问题。如果您使用全局变量,你models.py应该是这样的:

DEFAULT_SAMMICH = 0.3 

class Sammich(models.Model): 
    name = models.CharField(max_length=200) 
    ratio_of_cheese_to_meat = models.FloatField(default=DEFAULT_SAMMICH) 

class DeliSammich(models.Model): 
    sammich = models.ForiegnKey(Sammich) 
    type_of_meat = models.CharField(max_length=200) 
    type_of_cheese = models.CharField(max_length=200) 
    ratio_of_cheese_to_meat = models.FloatField(default=DEFAULT_SAMMICH) 
+1

这不正好解决我的问题。如果用户将Sammich实例中的ratio_of_cheese_to_meat设置为0.5,我希望与Sammich实例关联的DeliSammich实例的默认ratio_of_cheese_to_meat为0.5。 – Brian 2014-12-05 23:36:32

+0

@布里恩点好了。 * alecxe *的上述答案是正确的处理该方法的django方式。 – 2014-12-06 01:30:39

1

一种选择将是override the model's save() method和得到默认:

class DeliSammich(models.Model): 
    sammich = models.ForeignKey(Sammich) 
    type_of_meat = models.CharField(max_length=200) 
    type_of_cheese = models.CharField(max_length=200) 
    ratio_of_cheese_to_meat = models.FloatField() 

    def save(self, *args, **kwargs): 
     if not self.ratio_of_cheese_to_meat: 
      self.ratio_of_cheese_to_meat = self.sammich.ratio_of_cheese_to_meat 
     super(DeliSammich, self).save(*args, **kwargs) 
相关问题