首页 > 解决方案 > 我怎样才能显示真实的产品价格和折扣价

问题描述

我的 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()了,例如price200 美元和discount_percent25 美元,我如何显示变成 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

标签: djangodjango-modelsdjango-viewsdjango-templates

解决方案


这是一个例子,

考虑这些模型:

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()

推荐阅读