multiplication in django template without using manually created template tag

后端 未结 3 1176
情歌与酒
情歌与酒 2020-12-09 16:46

I want to achieve multiplication operation in django template. For example I have the values, price=10.50 quantity=3

With the help of this link

h

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-09 17:22

    Another approach that I have used seems cleaner to me. If you are going through a queryset, it doesn't make sense to compute the values in your view. Instead, add the calculation as a function in your model!

    Let's say your model looks like this:

    Class LineItem:
        product = models.ForeignKey(Product)
        quantity = models.IntegerField()
        price = models.DecimalField(decimal_places=2)
    

    Simply add the following to the model:

        def line_total(self):
            return self.quantity * self.price
    

    Now you can simply treat line_total as if it were a field in the record:

    {{ line_item.line_total }}
    

    This allows the line_total value to be used anywhere, either in templates or views, and ensures that it is always consistent, without taking up space in the database.

提交回复
热议问题