簡體   English   中英

Django模型中的計算

[英]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模型的priceProductPackage模型的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM