Home > Net >  How to use model functions in Views for multiple instances in Django?
How to use model functions in Views for multiple instances in Django?

Time:03-02

I have a Blog Post Model and I have defined a function to calculate the no of likes.

The Model is as follows ->

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.PROTECT)
    title = models.CharField(max_length=255)   
    description = models.CharField(max_length=1000,null=True)
    Tags = models.CharField(max_length = 255,null=True,blank=True)
    Created_date = models.DateTimeField(auto_now_add=True)
    Updated_date = models.DateTimeField(auto_now=True)
    category = models.ForeignKey(Category, on_delete=models.PROTECT)
    Likes = models.ManyToManyField(to=User, related_name='Post_likes')

    def __str__(self):
        return self.title

    def likesCount(self):
        return self.Likes.count()

Now I am querying the Post Model from the DB to get all the Posts as follows ->

posts =  Post.objects.select_related().prefetch_related('images_set','comments_post').annotate(Count('comments_post')).all()

Here when I loop over the posts I can call the likesCount function and it gives me the correct result as well but I want to return the No of likes to the template. How can I do that?

CodePudding user response:

in your template, try this:

{{ post.likes_set.count }}

and please make the field names lowercase, they are not Classes

  • Related