M
M
mkone1122021-10-18 05:53:54
Django
mkone112, 2021-10-18 05:53:54

How to combine Case and Count in annotation?

There are associated models, suppose a product model that has a buyer.

class Customer(models.Model):
    ...

class Product(models.Model):
    customer = models.ForeignKey(Customer, related_name='customer')
    date_sell = models.DateField(...)

I want to determine for each product purchased by the user whether this user has purchased products before. To do this, I perform the annotation twice, first counting the previous purchases, and then, depending on the result, add a second annotation.

Product.objects.annotate(
    prev_purchase_count=Count(
        'customer__product__id',
        filter=Q(
            customer__product__date_start__lte=F('date_start'),
        ) & ~Q(id=F('customer__product__id'))
    ),
).annotate(
    purchase_type=Case(
        When(prev_purchase_count=0, then=Value('Первая покупка')),
        default=Value('Повторная покупка'),
        output_field=TextField(),
    )
)

Question - is there a more elegant way to do this?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question