Answer the question
In order to leave comments, you need to log in
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(...)
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(),
)
)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question