简体   繁体   English

Django模型中的计算

[英]Calculation in django model

Here is my 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(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

The problem is with package_price field. 问题出在package_price字段。 It calculates package_price that is based on price of Consignment model and ammount_in_package of ProductPackage model. 它根据Consignment模型的priceProductPackage模型的ammount_in_package来计算package_price But this code throws and error when makemigrations ForeignKey' object has no attribute 'volume' And will package_price will be showing in admin page? 但是,当makemigrations ForeignKey' object has no attribute 'volume'时,此代码将引发错误,并且package_price将显示在admin页面中吗? I don't need it, because it calculates automatically, admin doesn't have to be allowed to change it. 我不需要它,因为它会自动计算,因此不必让管理员更改它。

package_price should be a property like this: package_price应该是这样的属性:

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

You can show this property in admin by adding it to the list_display . 您可以通过将其添加到list_display来在admin中显示该属性。 And, of course, it is not editable in admin :-) 而且,当然,它不能在admin中编辑:-)

You need to do that in get / set methods or consider using a property (which I would not advise anyway): 您需要在get / set方法中做到这一点,或考虑使用property (无论如何我都不会建议):

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

package_price = property(_get_package_price)

See the Django docs for more. 有关更多信息,请参见Django文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM