django - 模板中的 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问题,在视图中,您最好使用子句 [Django-doc]Post
检索s :.prefetch_related(..)
posts = Post.objects.prefetch_related('postphoto_set')
推荐阅读
- java - 根据每个字符串的子字符串对字符串 ArrayList 的一半进行排序
- angular - Angular - Rxjs Observable - 点击事件实现
- python - 正则表达式 - 获取数据直到第一次出现两个不同的序列
- sql - Oracle Sql:仅按 id 和日期选择最新记录
- r - 如何在 R 中快速调用多个具有相同名称的数据帧/向量,除了结尾
- javascript - HTML 脚本标记功能未在内联 onchange 属性中读取
- java - 命名查询中的字符串日期生成 ClassCastException
- javascript - 风格拖鬼元素
- php - 如何使用 symfony 表单创建微调器字段?
- unity3d - 无效的输出语义“SV_POSITION”:合法索引在 [0,0] 中