【发布时间】:2020-08-10 05:00:37
【问题描述】:
我有一个页面,其中列出了帖子以及与每个帖子相关的照片。但是,我在从照片列表 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)
【问题讨论】:
-
请分享相关模型。
-
@WillemVanOnsem 我已经编辑并添加了相关模型。
标签: django django-views django-templates django-queryset