首页 > 解决方案 > 模板中的 Django 动态对象过滤问题

问题描述

我有一个页面,其中列出了帖子以及与每个帖子相关的照片。但是,我在从照片列表 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)

标签: djangodjango-viewsdjango-templatesdjango-queryset

解决方案


您可以通过以下方式获取相关 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问题,在视图中,您最好使用子句 [Django-doc]Post检索s :.prefetch_related(..)

posts = Post.objects.prefetch_related('postphoto_set')

推荐阅读