编程语言
首页 > 编程语言> > python-Django.外键的默认值

python-Django.外键的默认值

作者:互联网

我使用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

我想使用默认价格= item.price创建Lot对象.即购买时的价格.因此我无法从Lot.item.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'

我应该如何纠正此代码?

解决方法:

您应该覆盖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)

标签:foreign-keys,python,django,django-models
来源: https://codeday.me/bug/20191119/2033941.html