Reputation: 79
I have class:
class Like(models.Model):
user = models.ForeignKey(User, related_name='likes', on_delete=models.CASCADE)
post = models.ForeignKey(Post, related_name='likes', on_delete=models.CASCADE)
ratingtype = models.IntegerField(default=0)
that lets me display total amount of lines in database table with this tag:
{{post.likes.count}}
What would be the best way to modify this class so i can differentiate the counting by two ratingtype (1 or 0)
Upvotes: 2
Views: 40
Reputation: 477607
Don't make queries in the template. Templates are used for render logic, not business logic.
You can annotate the Post
object(s) you are fetching with:
from django.db.models import Count, Q
Post.objects.annotate(
likes0=Count('likes', filter=Q(ratingtype=0)),
likes1=Count('likes', filter=Q(ratingtype=1))
)
The Product
s that arise from this queryset will have two extra attributes: .likes0
and .likes1
that contains the number of likes
with ratingtype=0
and ratingtype=1
respectively. You thus can then render this with:
{{ post.likes0 }}
{{ post.likes1 }}
Upvotes: 1