我有以下代码段。我首先尝试直接获取男性/女性人数作为注释,但我没有设法得到这些。因此,我编写了以下for循环。但是,仍然感觉这种解决方案并不尽如人意。您还有其他想法如何在此处编写更好的代码吗?
genders = self.get_answers(self.get_super_guests(), QuestionFocus.GENDER)
# >>> <QuerySet [Answer: Male, Answer: Female, Answer: Male]>
male = female = 0
for gender in genders:
if gender.answer == "Male":
male += 1
elif gender.answer == "Female":
female += 1
print("Gender distribution is Male", male, "Female: ", female)
答案 0 :(得分:5)
您可以使用项数来注释查询集的值,例如:
result = genders.values('answer').annotate(
number=Count('answer')
).order_by('answer')
这将导致QuerySet
如下所示:
<QuerySet [
{ 'answer': 'Male', 'number': 14},
{ 'answer': 'Female', 'number': 25}
]>
答案 1 :(得分:1)
# if your model name is QuestionFocus, then your query should be like this
QuestionFocus.objects.values('answer').annotate(number=Count('answer'))