Be careful when feeding multiple arguments to annotate() method(Django ORM) or using it in chain… it seems it does not return correct answers.
See the link below from stackoverflow:
As an example from Mosh course(Django p1):
Consider the customer with id 214, named ‘Carlin Doggrell’, her order ids are: 954, 936, 890, 382, 205(as you can see there are 5 orders placed by her)
When trying to calculate total number of orders placed by her, you can use annotate() this way:
customer = Customer.objects.all().annotate(total_orders=Count(F(‘order__id’)))
and this returns a correct answer… but when you feed another argument to annotate(), it seems it returns a wrong answer. for example:
customers = Customer.objects.all().annotate(total_orders=Count(F(‘order__id’)),
total_order_items=Count(F(‘order__orderitem__id’)))
here the total number of orders(for customer with id=214) changes to 11(being 5 and 5 is the correct answer), 9 is the total order items in her orders and it is correct(checked them inside the database). It seems for solving this problem, we have to set Count() distinct keyword to True as follows:
customers=Customer.objects.all().annotate(total_orders=Count(F(‘order__id’),
distinct=True),
total_order_items=Count(F(‘order__orderitem__id’)))
Is it a good idea or we would be better not to use annotate() with multiple arguments?