Ask Your Question
1

What is the method to apply two aggregation operations to lookup the same model?

asked 2023-07-15 09:40:04 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-07-15 09:56:02 +0000

lakamha gravatar image

To apply two aggregation operations to lookup the same model, we can use the chaining method in Django's ORM. We can chain two or more aggregation functions by calling the second function on the result of the first function, and so on.

For example, to get the total count of records and the sum of a numeric field (e.g. price) in a model named Employee, we can use the following code:

from django.db.models import Sum, Count
from myapp.models import Employee

result = Employee.objects.aggregate(
    count=Count('id'),
    total=Sum('price')
)

Here, we first call the Count function to get the count of Employee records and name it as 'count'. Then we call the Sum function to get the sum of the 'price' field and name it as 'total'. The result will be a dictionary with the keys 'count' and 'total' and their respective values.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-15 09:40:04 +0000

Seen: 14 times

Last updated: Jul 15 '23