[英]Calculation in django model
這是我的模型:
class Consignment(models.Model):
number = models.IntegerField(unique=True)
creation_date = models.DateTimeField()
expiration_date = models.DateTimeField()
package_ammount = models.IntegerField()
price = models.DecimalField(max_digits=12, decimal_places=2)
volume = models.DecimalField(max_digits=8, decimal_places=3)
image = models.ImageField()
brand = models.ForeignKey(Brand)
def __unicode__(self):
return self.brand.name + ' ' + str(self.volume) + ' liters'
class ProductPackage(models.Model):
consignment = models.ForeignKey(Consignment)
ammount_in_package = models.IntegerField()
total_volume = consignment.volume*ammount_in_package
total_width = models.DecimalField(max_digits=6, decimal_places=3)
total_height = models.DecimalField(max_digits=6, decimal_places=3)
total_length = models.DecimalField(max_digits=6, decimal_places=3)
package_price = consignment.price*ammount_in_package
問題出在package_price
字段。 它根據Consignment
模型的price
和ProductPackage
模型的ammount_in_package
來計算package_price
。 但是,當makemigrations
ForeignKey' object has no attribute 'volume'
時,此代碼將引發錯誤,並且package_price
將顯示在admin
頁面中嗎? 我不需要它,因為它會自動計算,因此不必讓管理員更改它。
package_price
應該是這樣的屬性:
class ProductPackage(models.Model):
...
@property
def package_price(self):
return self.consignment.price * self.ammount_in_package
您可以通過將其添加到list_display
來在admin中顯示該屬性。 而且,當然,它不能在admin中編輯:-)
您需要在get
/ set
方法中做到這一點,或考慮使用property
(無論如何我都不會建議):
def get_package_price(self):
return consignment.price*ammount_in_package
package_price = property(_get_package_price)
有關更多信息,請參見Django文檔 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.