thesteve
thesteve

Reputation: 2503

Annotate and Aggregate function in django

In django I have the following tables and am trying to count the number of votes by item.

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


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

I have the following queryset

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

that returns a list with item name and view count but not the item object. How can I set it up so that the object is returned instead of just the string value? I have been messing around with Manager and Queryset methods, that the right track? Any advice would be appreciated.

Upvotes: 1

Views: 626

Answers (1)

Radovan
Radovan

Reputation: 29

You can try something this:

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

To get the count value of first Vote object:

queryset[0].t_count

or to get Item object:

Item.objects.annotate(i_count=Count('votes'))

Upvotes: 2

Related Questions