📅  最后修改于: 2023-12-03 15:30:28.927000             🧑  作者: Mango
When working with Django QuerySets, sometimes we need to group results by a particular column and count how many times each value appears in that column. This can be achieved using the .annotate()
and .values()
methods on a queryset.
Firstly, we need to .annotate()
the queryset with the aggregated count of each value in the desired column. We then .values()
the column we want to group by and the count we just annotated. Finally, we can .order_by()
the count to get the results in descending order.
Here's an example using a Car
model:
from django.db.models import Count
cars = Car.objects.all().annotate(count=Count('make')).values('make', 'count').order_by('-count')
This queryset will return a list of dictionaries, where each dictionary contains the 'make' and 'count' values.
We can further filter the results using .filter()
before or after the annotation:
cars = Car.objects.filter(sold=True).annotate(count=Count('make')).values('make', 'count').order_by('-count')
This would only count the number of sold cars for each make.
Using .annotate()
, .values()
, and .order_by()
allows us to perform group by count operations on Django QuerySets. By chaining these methods together we can easily retrieve the data we need in a concise and efficient manner.