django - 如何在 Django 中显示最大折扣产品?
问题描述
我的数据库中有products
表格,并且有两列带有totalprice
和saleprice
,当我从后端添加产品时,我提交了两个价格。我想计算产品的最高报价(计算报价逻辑将是这样的,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)
解决方案
您可以 像这样在查询集中使用注释。
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)
推荐阅读
- c++ - 使用随机数生成器选择数组值
- google-cloud-platform - 谷歌云中的自动扩缩实例
- spring-boot - Spring Security 标记库不适用于 JSF
- python - 访问多索引数据框中的列
- twitter-bootstrap - BootstrapVue 垂直对齐内容的最佳方式?
- c++ - updatePointCloud-function 导致 vector::reserve 的 std::length_error
- html - 内联多行文本
- database - MongoDB 根据数组列表过滤单个值
- reactjs - 如何在生产中为 Docs 插件的 React Storybook 启用 prop-types
- python - 如何从 pymysql.cursor.description 获取所有数据类型的映射?