A
A
Andrey Salnikov2016-07-07 14:29:23
Django
Andrey Salnikov, 2016-07-07 14:29:23

How to call a function instead of an attribute in Django?

There is a model:

class Product(models.Model):
    price = models.FloatField('Цена')
    discount = models.IntegerField('Скидка')

When called in the object.price template, the price without the discount is displayed, which is correct. How can I display the discounted price?
Yes, I know you can write a method like get_price_with_discount and take the discount and price in it and display the result. Is there any way to do this with just the price? What would the discount be checked before its withdrawal?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sim3x, 2016-07-07
@Shshzik

# https://docs.python.org/3/library/decimal.html
from decimal import Decimal


class Product(models.Model):
    price = models.DecimalField('Цена')  
    # подумай, почему никто никогда не использует флоат для денег
    discount = models.IntegerField('Скидка')
    
    def get_price_with_discount(self):
         return self.price * Decimal(self.discount)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question