如何获取查询集中对象的数量? (姜戈)
如何添加相关对象计数字段?
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()
查找 contestA
的投票:
current_vote = Item.objects.filter(votes__contest=contestA)
它返回包含所有投票的查询集。如何获取每个 Item
的相关投票数?
How can I add a field for the count of related objects?
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()
To find the votes for contestA
:
current_vote = Item.objects.filter(votes__contest=contestA)
which returns a queryset with all of the votes. How do I get the count of related votes for each Item
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
要获取特定项目的票数,您可以使用:
如果您想详细了解特定竞赛中的票数分布,我会执行如下操作:
这将创建将项目映射到票数的字典。这不是唯一的方法,但它对数据库的命中率相当低,因此运行速度很快。
To get the number of votes for a specific item, you would use:
If you wanted a break down of the distribution of votes in a particular contest, I would do something like the following:
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.
另一种方法是使用聚合。您应该能够使用单个查询获得类似的结果。例如:
我没有测试这个特定的查询,但这应该以字典的形式输出竞赛中每个值的项目计数。
Another way of doing this would be using Aggregation. You should be able to achieve a similar result using a single query. Such as this:
I did not test this specific query, but this should output a count of the items for each value in contests as a dictionary.
使用相关名称来计算特定竞赛的选票
Use related name to count votes for a specific contest
您可以使用 len() 来获取contestA的票数:
实际上,
len()
与select_for_update() 如下所示:因为
select_for_update()
不使用count()
如下所示:您可以看到 我的回答解释了
select_for_update()
和count( )
或len()
。You can use len() to get the count of contestA's votes:
Actually,
len()
is used with select_for_update() as shown below:Because
select_for_update()
doesn't work withcount()
as shown below:You can see my answer explaning about
select_for_update()
withcount()
orlen()
.