模板中的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)

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

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

最新更新