![](/img/trans.png)
[英]Django. Access the foreign key fields in the template from a form object
[英]Django. Default value from foreign key
我使用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
我想創建Lot對象,默認price = item.price
。 即購買時的價格。 所以我無法從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'
我該如何更正此代碼?
模型定義中的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
您應該覆蓋Lot.save
以設置price的默認值。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.