Consultas Django Conditionals

class Order(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    customer = models.ForeignKey(Person, related_name="orders",on_delete=models.CASCADE)
    total = models.PositiveIntegerField()

aplicando un descuento a los clientes antiguos

from django.utils import timezone

orders = Order.bjects.filter(created_at__date=timezone.now().date()

for order in orders():
    customer_joined_year = order.customer.joined_on.year
    if(customer_joined_year >= 2010 and customer_joined_year <2019):
        order.total *=0.8
        order.save()
    elif(customer_joined_year <= 2000 and cutomer_joined_year >= 1995):
        order.total *= 0.6
        order.save()

ahora la versión con Conditionals

from django.db.models import Case, When

orders.annotate(discounted_total=
    Case(
        When(customer__joined_on__year__range=(1995, 2018),
            then=F("total") * 0.8,), 
        When(customer__joined_on__year__range=(1995, 2000),
            then=F("total") * 0.6,),
        default="total",)
)
      

Extraído de

DjangoCon 2019 – Building effective Django queries with expressions by Vanessa Barreiros – YouTube

Deja un comentario