django - 我怎样才能显示真实的产品价格和折扣价
问题描述
我的 html :
{% for stock in stocks %}
<p> size : {{stock.size}}</p>
{% for dis in discount %}
price : {{stock.price}} and Discount Percent : {{dis.discount_percent}}%
{% endfor %}
{% endfor %}
我使用第一个循环是因为我的产品可以有两种不同的尺寸,第二个循环只是因为我使用objects.filter()
了,例如price
200 美元和discount_percent
25 美元,我如何显示变成 150 美元的折扣价?
楷模:
class Product(models.Model):
product_model = models.CharField(max_length=255, default='')
...
class Stock(models.Model):
ONE = '1'
TWO = '2'
FREE = 'free'
PRODUCT_SIZES = [
(ONE, '1'),
(TWO, '2'),
(FREE, 'free'),
]
size = models.CharField(max_length=60,default=" ", choices=PRODUCT_SIZES)
quantity = models.PositiveIntegerField(default=0)
price = models.FloatField(default=0, null=True)
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product")
class Discount(models.Model):
name = models.CharField(max_length=255, default='')
items = models.ManyToManyField(Product, blank=True)
discount_percent = models.IntegerField(default=0,
validators=[
MaxValueValidator(100),
MinValueValidator(1),
]
)
def __str__(self):
return self.name
解决方案
这是一个例子,
考虑这些模型:
class Product(models.Model):
title = models.CharField(max_length=100)
price = models.FloatField()
discount_percentage = models.FloatField(blank=True, null=True)
description = models.TextField()
image = models.ImageField()
stock = models.IntegerField()
def __str__(self):
return self.title
class OrderItem(models.Model):
item = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
def __str__(self):
return f"order of {self.item.title}"
def get_total_item_price(self):
"""calculate price by quantity ,ex 4 phone of 100$ would be 400$ """
return self.quantity * self.item.price
def get_item_price_after_discount(self):
"""calculate price with discount ,ex 1 phone of 100$ with 25% would be 100*0.25 = 75$ """
return self.item.price * self.item.discount_percentage
def get_total_discount_item_price(self):
"""calculate price by quantity with discount ,ex 4 phone of 100$ with 25% would be 400*0.25 = 300$ """
return self.quantity * self.get_item_price_after_discount()
def get_difference_price_after_discount(self):
""",ex 4 phone of 100$ with 25% would be (400$ - 400*0.25 = 100$) """
return self.get_total_item_price() - self.get_total_discount_item_price()
推荐阅读
- python - 为什么我得到“方法 DESCRIBE 失败:401 未经授权”
- django - django 使用 for 循环将表行数据保存到数据库
- r - 从序列列中选择特定序列
- c# - SocketLab NotificationAPI 问题
- sql - 使用 SQL 将行转换为列
- apache-nifi - Nifi 在从 oracle 数据库读取时附加了额外的字符
- java - 从 POST 请求中检索数据时出错
- mongodb - “没有反应堆在运行,必须从 Tokio 1.x 运行时的上下文中调用”当将 mongodb 2 与 actix-web 3 一起使用时
- excel - Excel VBA - Financial Model Color Formatting
- kubernetes - 如何识别 statefulset 中不健康的 pod