Django的。外键的默认值

时间:2016-01-19 17:29:33

标签: python django django-models foreign-keys

我使用Django 1.9.1,Python 3.5。 models.py

class Item(models.Model):
    name = models.CharField(max_length=200)
    price = models.FloatField()
    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Lot(models.Model):
    item = models.ForeignKey(Item)
    count = models.IntegerField(default = 1)
    price = models.FloatField(default = 1) #Price on the moment of buying
    def __str__(self):              # __unicode__ on Python 2
        return self.item.name

    def cost(self):
         return self.price * self.count

我想用默认price = item.price创建Lot对象。即购买时的价格。所以我无法从Lot.item.price获得price值,因为它可能不同。当models.py的代码是这样的时候:

class Lot(models.Model):
    item = models.ForeignKey(Item)
    count = models.IntegerField(default = 1)
    price = models.FloatField(default = item.price) #Price on the moment of buying
    def __str__(self):              # __unicode__ on Python 2
        return self.item.name

    def cost(self):
         return self.price * self.count

我收到以下错误:

AttributeError: 'ForeignKey' object has no attribute 'price'

我该如何更正此代码?

2 个答案:

答案 0 :(得分:2)

模型定义中的

default不是“实例感知”。我建议覆盖Lot的保存方法,以便在保存时提取价格。

class Lot(models.Model):

    item = models.ForeignKey(Item)
    count = models.IntegerField(default = 1)
    price = models.FloatField(default = item.price) #Price on the moment of buying
    def __str__(self):              # __unicode__ on Python 2
        return self.item.name

    def save(self, *args, **kwargs):
        if self.item: # verify there's a FK
            self.price = self.item.price
        super(Lot, self).save(*args,**kwargs) # invoke the inherited save method; price will now be save if item is not null

    def cost(self):
         return self.price * self.count

答案 1 :(得分:1)

您应该覆盖Lot.save以设置价格的默认值。

class Lot(models.Model):
    item = models.ForeignKey(Item)
    price = models.FloatField()
    ....

    def save(self, *args, **kwargs):
        if not self.price:
            self.price = self.item.price
        super(Lot, self).save(*args, **kwargs)