在 Django 的模板中显示模型的计算值

Jas*_*ngh 0 django django-templates django-models

我想在每个产品下显示计算的折扣。下面的代码没有错误,但不显示值。

模型.py

from django.db import models
# Create your models here.
CATEGORIES = (  
    ('Electronics', 'Electronics'),
    ('Clothing', 'Clothing'),
)

class Products(models.Model):
    Image = models.FileField()
    ProductName = models.CharField(max_length = 250, default='')
    Brand = models.CharField(max_length = 250, default='')
    OriginalPrice = models.IntegerField(default = '')
    Price = models.IntegerField(default = '')
    Category = models.CharField(max_length = 250, choices = CATEGORIES)

    class Meta:
        verbose_name = 'Product'
        verbose_name_plural = 'Products'

    def DiscountCalc(self):
        Discount = (Price/OriginalPrice) * 100
        return self.Discount

    def __str__ (self):
        return self.ProductName
Run Code Online (Sandbox Code Playgroud)

这是模板 index.html

{% for product in AllProducts %}
    <article class="product col-sm-3">
        <a href="#" class="prodlink">
            <img src="{{ product.Image.url }}" class="prodimg img-responsive">
            <p class="prodname">{{ product.ProductName }}</p>
            <span class="origprice">?{{ product.OriginalPrice }}</span>
            <span class="price">?{{ product.Price }}</span>
            <div class="discount">
                <p>{{ product.Discount }}% off</p>
            </div>
        </a>
    </article>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

小智 5

你需要创建一个属性:

@property
def Discount(self):
    return (self.Price/self.OriginalPrice) * 100
Run Code Online (Sandbox Code Playgroud)

所以现在你可以使用 product.Discount :)

文档在这里Django 模型方法