Django:如何将字段的默认值设置为父模型中字段的值

时间:2014-12-05 22:41:58

标签: django django-models

说我有以下型号

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)

哪个不起作用。

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:-1)

您可以使用全局变量来解决这个问题。如果您使用全局变量,则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)