0

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)

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Ok I got it, thank you. There should be item_list = item_list.filter(current_price__gte=price_from) , at least thats what worked for me. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.