2015-04-25 80 views
0

這裏是我的模型:計算在Django模型

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領域。它計算package_price是基於priceConsignment模型和ammount_in_packageProductPackage模型。但是這段代碼會拋出並且錯誤時makemigrationsForeignKey' object has no attribute 'volume' 而且package_price會在admin頁面顯示嗎?我不需要它,因爲它會自動計算,因此不必允許管理員更改它。

回答

2

package_price應該是這樣的一個屬性:

class ProductPackage(models.Model): 
    ... 
    @property 
    def package_price(self): 
     return self.consignment.price * self.ammount_in_package 

您可以將它添加到list_display顯示在管理該屬性。而且,當然,它不是在管理編輯:-)

0

你需要做的是,在get/set方法或考慮使用property(我會提醒反正):

def get_package_price(self): 
    return consignment.price*ammount_in_package 

package_price = property(_get_package_price) 

有關更多信息,請參閱the Django docs