模板中的Django动态对象过滤问题。

问题描述 投票:0回答:1

我有一个页面,其中列出了帖子以及与每个帖子相关的照片。然而,我在过滤和发送照片列表QuerySet中遇到了麻烦,因为它是在帖子列表查询集的循环下进行的。任何想法,如何运行过滤器,以获得照片作为模板中只有相关的帖子?

<h2> Posts: </h2>
{% for post in post_list %}

     {% include 'posts/list-inline.html' with post_whole=post  post_photos=photo_list %}

{% endfor %}

在这里,从photo_list中需要过滤掉与单个帖子有外键关系的多个对象,QuerySet过滤器在模板中不起作用。

更新:缩小后的模型供参考。

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post_text = models.CharField(max_length=5000, null=True, blank=True)
    selection = models.ForeignKey(Selection, null=True, blank=False, on_delete=models.SET_NULL)
    timestamp = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

class PostPhoto(models.Model):
    # to apply multiple photos to same post id
    post_id = models.ForeignKey(Post, null=True, blank=True, on_delete=models.CASCADE)
    photo = models.ImageField(upload_to='img/', blank=True, null=True)
    thumbnail = models.ImageField(upload_to='tmb/', null=True, blank=True, editable=False)
django django-views django-templates django-queryset
1个回答
2
投票

您可以从以下列表中获取 相关 PostPhoto 对象。

mypost.postphoto_set.all()

所以在你的模板中,你可以用:

<h2> Posts: </h2>
{% for post in post_list %}
     {% include 'posts/list-inline.html' with post_whole=post  post_photos=post.postphoto_set.all %}
{% endfor %}

(不加括号,因为模板会自动调用一个可调用的对象)。

为了避免使用 N+1 问题,在视图中,你最好检索到的是 Post设有 .prefetch_related(..) 条款[Django-doc]:

posts = Post.objects.prefetch_related('postphoto_set')
© www.soinside.com 2019 - 2024. All rights reserved.