Andrew
Andrew

Reputation: 443

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. It calculates package_price that is based on price of Consignment model and ammount_in_package ofProductPackage model. But this code throws and error when makemigrations ForeignKey' object has no attribute 'volume' And will package_price will be showing in admin page? I don't need it, because it calculates automatically, admin doesn't have to be allowed to change it.

Upvotes: 0

Views: 649

Answers (2)

Tobia Tesan
Tobia Tesan

Reputation: 1936

You need to do that in get/set methods or consider using a property (which I would not advise anyway):

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

package_price = property(_get_package_price)

See the Django docs for more.

Upvotes: 0

catavaran
catavaran

Reputation: 45595

package_price should be a property like this:

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. And, of course, it is not editable in admin :-)

Upvotes: 2

Related Questions