2014-12-05 102 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) 
相關問題