Python django模型的计算

Python django模型的计算,python,django,python-2.7,django-models,Python,Django,Python 2.7,Django Models,这是我的模型: class Consignment(models.Model): number = models.IntegerField(unique=True) creation_date = models.DateTimeField() expiration_date = models.DateTimeField() package_ammount = models.IntegerField() price = models.DecimalField

这是我的模型:

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\u price
字段。它计算基于
寄售
模型的
价格
产品包
模型的
包装
中的
金额的
包装价格
。但是当
makemigrations
ForeignKey'对象没有属性“volume”时,此代码抛出并出错

并且,
package\u price
是否会显示在
admin
页面?我不需要它,因为它是自动计算的,管理员不必允许更改它。

package\u price
应该是这样的属性:

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

您可以通过将此属性添加到
列表\u display
中,在admin中显示此属性。当然,它在Admin中是不可编辑的:-)/p>< p>您需要在<代码>获取< <代码> >代码> SET<代码>方法中,或者考虑使用<代码>属性< /> >(我无论如何都不建议):

更多信息,请参阅

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

package_price = property(_get_package_price)