【发布时间】:2016-04-25 07:26:42
【问题描述】:
我使用 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 对象。 IE。购买时的价格。所以我无法从 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'
我应该如何更正此代码?
【问题讨论】:
标签: python django django-models foreign-keys