I have this code in django that, for every django comment, does whatever is inside the for loop:
{% for comment in post.comments.all %}
{% endfor %}
This code, for every comment, does whatever is inside the for. To count the comments I use this:
{{ post.comments.count }}
This is my comment model in case you need it:
class Comment(models.Model):
post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(User, on_delete=models.CASCADE)
text = models.TextField(default='')
created_date = models.DateTimeField(default=timezone.now)
anonymous = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()
def __str__(self):
return self.text
Now, I want to sort of combine these together, so it shows only the latest 3 comments and only runs the for loop 3 times or less. (Please note that I want to do all of this work in the templates, and not in the views.py file)