问题描述
models.py
models.py
class Event(models.Model):
name = models.CharField(max_length=20, unique=True)
distance = models.IntegerField()
date = models.DateField()
class Category(models.Model):
name = models.CharField(max_length=20, unique=True)
description = models.CharField(max_length=20, unique=True)
isnew = models.BooleanField(default=False)
class Result(models.Model):
event = models.ForeignKey(Event)
category = models.ForeignKey(Category)
score = models.IntegerField()
对于给定的事件,我想执行一个查询以返回结果表中每个唯一类别的计数。
I want to do a query to return a count of each unique Category in the Result table, for a given Event.
我现在正在做的事情是这样的:
What I'm doing now is something like:
results = Result.objects.filter(event=myevent)
categorycountdict = {}
for r in results:
if r.category in categorycountdict:
categorycountdict[r.category] += 1
else:
categorycountdict[r.category] = 1
有没有更好的方法,也许可以通过查询代替python。
Is there a better way, perhaps by query instead of python.
推荐答案
您可以使用 annotate()
与 values()
。在。要获取每个类别名称的计数,您可以执行以下操作:
You can use annotate()
with values()
. This approach is shown in the docs for values()
. To get the count for each category name, you could do:
from django.db.models import Count
categories = Result.objects.filter(
event=myevent,
).order_by('category').values(
'category__name'
).annotate(count=Count('category__name'))
这将返回键为<$ c $的字典列表c> category__name 和 count
,例如:
This will return a list of dictionaries with keys category__name
and count
, for example:
[{'count': 3, 'category__name': u'category1'}, {'count': 1, 'category__name': u'category2'}]
您可以使用字典理解功能将其转换为单个字典:
You could convert this to a single dictionary by using a dictionary comprehension:
counts_by_category = {d['category__name']: d['count'] for f in categories}
这篇关于Django字段中的项目计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!