模板中的Django动态对象过滤问题 [英] Django Dynamic Object Filtering issue in Template

查看:47
本文介绍了模板中的Django动态对象过滤问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a page which lists the posts along with the photos associated with each post. However I am having trouble in filtering and sending photos from photo lists QuerySet as it us under loop of posts list query set. Any idea how to run filters for getting the photos as only the associated post in a template?

<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过滤器在模板中的此处不起作用.

Here from photo_list in need to filter out multiple objects having foreign key relationship with individual post. The QuerySet filter is not working here in the template.

更新:缩小模型以供参考:

Update: The shrunken down models for reference:

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 对象的列表:

You can obtain the lists of related PostPhoto objects with:

mypost.postphoto_set.all()

因此,在您的模板中,您可以使用以下方法呈现该图片:

So in your template, you can render this with:

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

(不带括号,因为模板会自动调用可调用对象).

(without brackets, since the template will automatically call a callable).

为避免出现 N + 1 问题,在视图中,最好使用Post .com/en/dev/ref/models/querysets/#prefetch-related"rel =" nofollow noreferrer> .prefetch_related(..) 子句[Django-doc]:

To avoid the N+1 problem, in the view, you better retrieve the Posts with a .prefetch_related(..) clause [Django-doc]:

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

这篇关于模板中的Django动态对象过滤问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆