DanailYordanov
DanailYordanov

Reputation: 25

Django ordering by two fields not working as expected

i am working on a shop for clothes, shoes etc. And i am trying to sort the products by price. The problems comes when the product's discount_price field is populated which means that this product is discounted. So when i want to order the products in my view i am expecting to see products with lower discount_price before products with higher price, but it is not working like this.

models.py

class Item(models.Model):
    price = models.IntegerField(null=True, blank=True)
    discount_price = models.IntegerField(null=True, blank=True)

The query i am performing

items = Item.objects.all().order_by('price', 'discount_price')

Upvotes: 1

Views: 161

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

You can make use of Coalesce(..) [Django-doc] to first sort by 'discount_price' if it is not NULL, and use price otherwise:

from django.db.models.functions import Coalesce

items = Item.objects.order_by(Coalesce('discount_price', 'price').asc())

Upvotes: 1

Related Questions