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.
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
Asked: 2023-07-15 09:40:04 +0000
Seen: 14 times
Last updated: Jul 15 '23
What is the process to detect and count common elements in R?
How can I use Prometheus to count the number of distinct label values?
How to count relationship column in Laravel using GroupBy?
What is the total count of unique arrangements of key values that can be inserted into a hash table?
How can ReceivedTime in Outlook VBA be utilized to track the number of emails received yesterday?
How to count the total number of exported identifiers using the eslint rule?
What is the method to execute React useEffect hook just once when there is a modification in state?