Answer the question
In order to leave comments, you need to log in
How to optimally filter on an optional related table?
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.filter(price__range=(10, 80))
products = Product.objects.annotate(price_with_sale=F('price')*(1-F('sale__percent')))
products = products.filter(price_with_sale__range=(10, 80))
def filter_prices(self, products, price_from, price_to):
products1 = Product.objects.filter(sale__isnull=True)
products1 = products1.filter(price__range=(price_from, price_to))
products2 = Product.objects.filter(sale__isnull=False)
products2 = products2.annotate(new_price=F('price')*(1-F('sale__percent')))
products2 = products2.filter(new_price__range=(price_from, price_to))
ids = list(chain(products1.values_list('id', flat=True), products2.values_list('id', flat=True)))
return products.filter(id__in=ids)
Answer the question
In order to leave comments, you need to log in
Product.objects.annotate(
price_with_sale=F('price')*(1-F('sale__percent'))
).filter(
Q(price__range=(10, 80)) | Q(price_with_sale__range=(10, 80))
)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question