Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

python - Is it possible to filter "Related field" in Django Template?

I am developing an Instagram clone using Django. I wanted to show the latest two comments for each post.

As of now, I am only able to show all comments using the below code

home.html

{% for comment in post.comments.all %}
   <p>{{ comment.user.username }}: {{ comment.description }}</p>
{% endfor %}

My models

class Comment(models.Model):

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post_linked = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
    description = models.CharField(max_length=500)
    comment_posted_on = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return "Comment by {} on {}".format(self.user.username, self.post_linked.caption)

Is there any way I cal display only the Latest two comment for each post?

question from:https://stackoverflow.com/questions/65905946/is-it-possible-to-filter-related-field-in-django-template

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should create the collection of filtered comments in your view, then include that in the template's context. Django's template philosophy is to make them as simple as possible which generally means no function calls (except for template tags and filters).

To make things a bit more efficient you should utilize prefetch_related and Prefetch. Checkout the docs on them for the best reference.

from django.db.models import Prefetch
posts = Post.objects.all().prefetch_related(
    Prefetch(
        'comments',
        Comment.objects.select_related('user').order_by('-comment_posted_on')[:2],
        to_attr='latest_comments',
    )
)

Then in your template:

{% for comment in post.latest_comments %}
   <p>{{ comment.user.username }}: {{ comment.description }}</p>
{% endfor %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...