1

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.

1 Answer 1

2

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'))
Sign up to request clarification or add additional context in comments.

2 Comments

This returns the count of the objects but not the object itself which I can call methods on. How can I link up the actual objects that are being aggregated?
you can access object queryset[0].user or for the sencond exmaple queryset[0].name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.