Home > Enterprise >  How to perform 'SELECT a or b < c FROM Table' on Django QuerySet?
How to perform 'SELECT a or b < c FROM Table' on Django QuerySet?

Time:02-05

I have the following model:

class DiscountCoupon(models.Model):
   is_used = models.BooleanField(default=False)
   expiration_date = models.DateField()

   def is_available(self):
      if self.used or self.expiration_date <= date.today():
         return False
      return True

Instead of calling the is_available method iterating through a QuerySet, I want to do this operation into the QuerySet to perform better, like this:

SELECT (used OR (expiration_date < Now())) AS is_available FROM randomapp_discountcoupon;

Is this possible?

CodePudding user response:

You can use Q objects [Django-doc] with Case[Django-doc] expression as

from django.db.models import Q, Case, Value, When

discount_objects = DiscountCoupon.objects.annotate(
    is_available=Case(
        When(Q(is_used=True) | Q(expiration_date__lt=datetime.date.today()), then=Value(True)), 
        default=Value(False),
        output_field=BooleanField()
     )
)
  •  Tags:  
  • Related