[Django]-Django Templates Display The Latest 3 Comments

3👍

You can order the comments by default by the creation date with:

from django.conf import settings

class Comment(models.Model):
    post = models.ForeignKey(
        'blog.Post',
        on_delete=models.CASCADE,
        related_name='comments'
    )
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )
    text = models.TextField(default='')
    created_date = models.DateTimeField(auto_now_add=True)
    anonymous = models.BooleanField(default=False)

    class Meta:
        ordering = ['-created_date']

    # …

Then you can work with the |slice template filter [Django-doc] to slice the queryset:

{% for comment in post.comments.all|slice:':3' %}

{% endfor %}

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

It is however better to prefetch the elements in the view, with:

Post.objects.prefetch_related('comments')

this will fetch the comments in bulk, which is more efficient than running a query per Post object.

Leave a comment