Menor
Menor

Reputation: 300

If statement in python/django

I am trying to do a simple if statement in python. I have got two fields in my model that corresponds to price (price and discount_price). I would like to filter the results by price but I am not sure how to write the if statement. It should go like this: If 'discount_price exists' then filter by using 'discount_price' if not use field 'price' instead.

my views.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)

Upvotes: 0

Views: 104

Answers (1)

iklinac
iklinac

Reputation: 15718

Use Coalesce to get first value that is set

from django.db.models.functions import Coalesce
.annotate(current_price=Coalesce('discount_price','price')).filter(current_price...)

Comment usage example

 item_list = item_list.annotate(current_price=Coalesce('discount_price','price'))
 if price_from:
    item_list = item_list.filter(current_price__gte=price_from)

Upvotes: 3

Related Questions