在Django的查询集中获取对象数量 [英] Getting a count of objects in a queryset in django

查看:405
本文介绍了在Django的查询集中获取对象数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为数据库中的对象计数添加字段。我有以下模型:

How can I add a field for the count of objects in a database. I have the following models:

class Item(models.Model):
    name = models.CharField()

class Contest(models.Model);
    name = models.CharField()

class Votes(models.Model):
    user = models.ForeignKey(User)
    item = models.ForeignKey(Item)
    contest = models.ForeignKey(Contest)
    comment = models.TextField()

要查找比赛A的选票,我在视图中使用以下查询

To find the votes for contestA I am using the following query in my view

current_vote = Item.objects.filter(votes__contest=contestA)

这将返回一个包含所有投票的查询集,但我想获得计数为每个项目投票,有人知道我该怎么做吗?谢谢

This returns a queryset with all of the votes individually but I want to get the count votes for each item, anyone know how I can do that? thanks

推荐答案

要获取特定项目的票数,请使用:

To get the number of votes for a specific item, you would use:

vote_count = Item.objects.filter(votes__contest=contestA).count()

如果您想细分特定比赛的票数分配,我会做以下事情:

If you wanted a break down of the distribution of votes in a particular contest, I would do something like the following:

contest = Contest.objects.get(pk=contest_id)
votes   = contest.votes_set.select_related()

vote_counts = {}

for vote in votes:
  if not vote_counts.has_key(vote.item.id):
    vote_counts[vote.item.id] = {
      'item': vote.item,
      'count': 0
    }

  vote_counts[vote.item.id]['count'] += 1

这将创建将项目映射到票数的字典。不是唯一的方法,但是数据库命中率很高,因此运行起来很快。

This will create dictionary that maps items to number of votes. Not the only way to do this, but it's pretty light on database hits, so will run pretty quickly.

这篇关于在Django的查询集中获取对象数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆