O
O
Oscar Django2016-03-18 12:23:59
Django
Oscar Django, 2016-03-18 12:23:59

How to optimally sort by an optional related table?

Let's continue the topic of filtering
that has already been started. I will duplicate the introductory part:
There are 2 tables:

class Sale(models.Model):
  percent = models.FloatField()

class Product(models.Model):
  sale = models.ForeignKey(Sale, null=True, blank=True)
  price = models.FloatField()

You need to sort items by price. At the same time, the discount can affect the price, i.e. the $120 item at 50% off ($60) must come before the $80 item when sorted in ascending order.
The trick from last time will not work, I guess, because. you can not sort by the field, and if it is NULL then take the value from another field. Or I'm wrong?
----------------------------
I'm definitely wrong
products = Product.objects.annotate(
    price_with_sale=F('price')*(1-F('sale__percent'))
).filter(
    Q(price__range=(10, 80, price_with_sale__isnull=True)) | Q(price_with_sale__range=(10, 80))
)
products = products.order_by(Coalesce('price_with_sale', 'price').asc())

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oscar Django, 2016-03-18
@winordie

Looks like I'm dumb

products = Product.objects.annotate(
    price_with_sale=F('price')*(1-F('sale__percent'))
).filter(
    Q(price__range=(10, 80, price_with_sale__isnull=True)) | Q(price_with_sale__range=(10, 80))
)
products = products.order_by(Coalesce('price_with_sale', 'price').asc())

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question