Getting a count of objects in a queryset in django

前端 未结 3 1827
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-24 04:40

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 Con         


        
3条回答
  •  感动是毒
    2020-12-24 05:20

    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.

提交回复
热议问题