首页 > 解决方案 > 如何在 Django 中显示最大折扣产品?

问题描述

我的数据库中有products表格,并且有两列带有totalpricesaleprice,当我从后端添加产品时,我提交了两个价格。我想计算产品的最高报价(计算报价逻辑将是这样的,offer=totalprice/saleprice),我想在我的网站 homegae 上显示这些产品,但我不知道如何在 Django 中做到这一点。请让我指导如何在views.py文件中添加逻辑。

这是我的views.py文件...

def home(request):
   product= Product.objects.filter(featured=True).order_by('-created_at')[0:8]
   subc=Product.objects.filter(discount=30).order_by('-created_at')
   return render(request, 'mainpage/index.html',
              {'product':product,'subc':subc})

这是我的models.py文件

class Product(models.Model):
   name=models.CharField(max_length=225)
   slug=models.SlugField(max_length=225, unique=True)
   subcategory=models.ForeignKey('SubCategory', related_name='prosubcat', on_delete=models.CASCADE, blank=True, null=True)
   totalprice=models.IntegerField()
   saleprice = models.IntegerField()
   title=models.CharField(max_length=225)
   description = models.TextField()
   overview = models.TextField(null=True)
   featured = models.BooleanField(null=True)
   trending=models.BooleanField(null=True)
   image= models.ImageField(blank=True)
   tags = TaggableManager()
   created_at = models.DateTimeField(auto_now_add=True)
   updated_at = models.DateTimeField(auto_now=True)

标签: djangodjango-modelsdjango-formsdjango-viewsdjango-templates

解决方案


您可以 像这样在查询集中使用注释。

from django.db.models import F
def home(request):
       products= Product.objects.filter(featured=True).annotate(offer=F('totalprice')-F('saleprice'))

现在在模板中你可以这样做:

{% for product in products %}
      Product Offer:{{ product.offer }}
{% endfor %}

编辑:要计算百分比,试试这个。

Product.objects.filter(featured=True).annotate(offer=((F('totalprice')-F('saleprice'))/F('totalprice'))*100)

推荐阅读