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

查看:36
本文介绍了在 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天全站免登陆