Jayesh
Jayesh

Reputation: 1523

Django Dynamic Object Filtering issue in Template

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 %}

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)

Upvotes: 1

Views: 66

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

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).

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')

Upvotes: 2

Related Questions