2015-04-25 82 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