python - python/django中的if语句
问题描述
我正在尝试在 python 中做一个简单的 if 语句。我的模型中有两个字段对应于价格(价格和折扣价格)。我想按价格过滤结果,但我不确定如何编写 if 语句。它应该是这样的:如果存在“discount_price”,则使用“discount_price”过滤,如果不使用“price”字段。
我的意见.py
def HomeView(request):
item_list = Item.objects.all()
category_list = Category.objects.all()
query = request.GET.get('q')
if query:
item_list = Item.objects.filter(title__icontains=query)
cat = request.GET.get('cat')
if cat:
item_list = item_list.filter(category__pk=cat)
price_from = request.GET.get('price_from')
price_to = request.GET.get('price_to')
if price_from:
item_list = item_list.filter(price__gte=price_from)
if price_to:
item_list = item_list.filter(price__lte=price_to)
paginator = Paginator(item_list, 10)
page = request.GET.get('page')
try:
items = paginator.page(page)
except PageNotAnInteger:
items = paginator.page(1)
except EmptyPage:
items = paginator.page(paginator.num_pages)
context = {
'items': items,
'category': category_list
}
return render(request, "home.html", context)
解决方案
使用Coalesce获取设置的第一个值
from django.db.models.functions import Coalesce
.annotate(current_price=Coalesce('discount_price','price')).filter(current_price...)
评论使用示例
item_list = item_list.annotate(current_price=Coalesce('discount_price','price'))
if price_from:
item_list = item_list.filter(current_price__gte=price_from)
推荐阅读
- scipy - 如何有效地将python中的数字存储为汇总表达式,而不会因舍入误差而丢失任何精度
- oracle - 在 WHERE IN 子句中使用 %ROWTYPE
- hive - PySpark 无法从 hdfs 读取 csv:HiveExternalCatalog 错误
- command-prompt - “packer.exe”不是内部或外部命令、可运行程序或批处理文件
- mysql - 用户''@'localhost'的访问被拒绝(使用密码:否) - Laravel
- java - 如何将文件保存到 Android Q(API 29)上的公共(外部)存储?
- android - 如何将此 HATEOAS 格式的 json 转换为 android 中的模型对象?
- javascript - 如何将 json 值转换为 c# 中的字典并使用字符串值对其进行寻址?
- angular - Angular 运行单一测试(不是 fdescribe 或 fit)
- node.js - 为什么将异步函数传递给 Node.js Express.js 路由器?