1

在 django 中,我有以下表格,并试图按项目计算投票数。

class Votes(models.Model):
    user = models.ForeignKey(User)
    item = models.ForeignKey(Item)


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

我有以下查询集

queryset = Votes.objects.values('item__name').annotate(Count('item'))

它返回一个包含项目名称和视图计数但不包含项目对象的列表。如何设置它以便返回对象而不仅仅是字符串值?我一直在搞乱 Manager 和 Queryset 方法,那是正确的轨道吗?任何意见,将不胜感激。

4

1 回答 1

2

你可以试试这个:

queryset = Votes.values.annotate(t_count=Count('item'))

要获取第一个 Vote 对象的计数值:

queryset[0].t_count

或获取 Item 对象:

Item.objects.annotate(i_count=Count('votes'))
于 2011-03-03T13:28:08.340 回答