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

时间:2017-06-02 13:13:21

标签: django django-models django-templates

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

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

这是模板 的的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 %}

2 个答案:

答案 0 :(得分:1)

你需要建立一个财产:

from app.models import Producto,Proveedor

productos = Producto.objects.all() # How do I do the filter ?
for producto in productos:
    nombre_producto = producto.nombre_producto
    proveedor = len(producto.proveedor)

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

此处的文档javadoc

答案 1 :(得分:0)

1)定义局部变量并返回类变量将返回null

2)你必须在模型和模板中使用相同的名称

models.py

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

的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.DiscountCalc }}% off</p>
            </div>
        </a>
    </article>
{% endfor %}