How can I count total likes?
Question:
I added a like button to my blog. It’s working perfectly but I can’t count the total number of likes present. What should I do now? How can I count the total number of likes?
models.py:
class FAQ(models.Model):
likes = models.ManyToManyField(User,default=None, related_name="faqLIKES")
views.py:
def index(request):
allFAQ = FAQ.objects.all()
context = {"allFAQ":allFAQ}
return render(request,'0_index.html',context)
Answers:
Use count.
>>> post.likes.count() # returns a count of all likes
Also, as a side note – why do you have a url parameter if you’re getting the id of the post to like inside the POST data? Why not only use the url parameter? You wouldn’t have to send any form data from the client side.
You can .annotate(…)
[Django-doc] with:
from django.db.models import Count
FAQ.objects.annotate(number_of_likes=Count('likes'))
The FAQ
objects that arise from this QuerySet
will have an extra attribute .number_of_likes
. In the template you thus can enumerate over the FAQ
objects, and render {{ faq.number_of_likes }}
with faq
a FAQ
object.
I added a like button to my blog. It’s working perfectly but I can’t count the total number of likes present. What should I do now? How can I count the total number of likes?
models.py:
class FAQ(models.Model):
likes = models.ManyToManyField(User,default=None, related_name="faqLIKES")
views.py:
def index(request):
allFAQ = FAQ.objects.all()
context = {"allFAQ":allFAQ}
return render(request,'0_index.html',context)
Use count.
>>> post.likes.count() # returns a count of all likes
Also, as a side note – why do you have a url parameter if you’re getting the id of the post to like inside the POST data? Why not only use the url parameter? You wouldn’t have to send any form data from the client side.
You can .annotate(…)
[Django-doc] with:
from django.db.models import Count
FAQ.objects.annotate(number_of_likes=Count('likes'))
The FAQ
objects that arise from this QuerySet
will have an extra attribute .number_of_likes
. In the template you thus can enumerate over the FAQ
objects, and render {{ faq.number_of_likes }}
with faq
a FAQ
object.