Answer the question
In order to leave comments, you need to log in
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()
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
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 questionAsk a Question
731 491 924 answers to any question