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 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 I am using the following query in my view
current_vote = Item.objects.filter(votes__contest=contestA)
This returns a queryset with all of the votes individually but I want to get the count votes for each item, anyone know how I can do that? thanks
This question is related to
django
django-models
django-queryset
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:
Item.objects.values("contest").annotate(Count("id"))
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
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, related_name="contest_votes")
comment = models.TextField()
>>> comments = Contest.objects.get(id=contest_id).contest_votes.count()
Source: Stackoverflow.com