[Fixed]-Iterate through certain number of foreign key objects

0πŸ‘

βœ…

I don’t think this is possible in templates. As you do not only want 5 comments but you also want to order them (latest 5). You can add a method in your BaseRecipe model class to get recent comments.

class BaseRecipe(models.Model):
    def get_recent_comments(self, n=5):
        return self.comment_link.all().order_by('-id')[:n]

Then call this method in your template

{% for comment in object.get_recent_comments %}

1πŸ‘

You can use slice

{% for comment in object.comment_link.all|slice:":10" %}
πŸ‘€itzMEonTV

Leave a comment