如何显示真实产品价格和折扣价

时间:2021-06-22 09:01:00

标签: django django-models django-views django-templates

我的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

1 个答案:

答案 0 :(得分:1)

这是一个例子,

考虑这些模型:

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()
相关问题