我使用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'
我该如何更正此代码?
答案 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)