【问题标题】:Calculation in django modeldjango模型中的计算
【发布时间】:2015-04-25 10:31:29
【问题描述】:

这是我的模型:

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 页面中?我不需要它,因为它是自动计算的,不必允许管理员更改它。

【问题讨论】:

    标签: python django python-2.7 django-models


    【解决方案1】:

    package_price 应该是这样的属性:

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

    您可以通过将其添加到list_display 来在管理员中显示此属性。而且,当然,它在管理员中不可编辑:-)

    【讨论】:

      【解决方案2】:

      您需要在 get/set 方法中执行此操作,或者考虑使用 property(无论如何我建议):

      def get_package_price(self):
          return consignment.price*ammount_in_package
      
      package_price = property(_get_package_price)
      

      请参阅the Django docs 了解更多信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-24
        • 1970-01-01
        相关资源
        最近更新 更多