首页 > 解决方案 > 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)

标签: pythondjango

解决方案


使用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)

推荐阅读