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

Django Dynamic Object Filtering issue in Template

我有一个页面列出了 post 以及与每个 post 相关的照片。但是,我在从照片列表 QuerySet 过滤和发送照片时遇到问题,因为我们在 posts 列表查询集的循环下。知道如何 运行 过滤器以仅将照片作为模板中的关联 post 获取吗?

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

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

{% endfor %}

此处来自photo_list需要过滤掉多个与个体post有外键关系的对象。 QuerySet 过滤器在模板中不起作用。

更新:sh运行ken down模型供参考:

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)

您可以获得 相关 PostPhoto 个对象的列表:

mypost<b>.postphoto_set.all()</b>

因此在您的模板中,您可以使用以下方式呈现:

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

(没有括号,因为模板会自动调用可调用对象)。

为避免 N+1 问题,在视图中,您最好使用 .prefetch_related(..) clause [Django-doc]:

检索 Posts
posts = Post.objects<b>.prefetch_related('postphoto_set')</b>