Skip to content
Advertisement

How do you get queryset objects related to queryset passed to templates in Django

I have these two models and as you can see they have a relationship.

class Post(models.Model):
    text = models.TextField()

class PostImage(models.Model):
    post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE)
    image = models.FileField(upload_to = 'media/',blank=True, null=True)

As far as I understand if I query posts and push them to a template and post, I would expect to use something like this in my templates to retrieve the images URL attached to the posts but it doesn’t seem to work.

{% for post in posts %}
    {% for post_image in post.post_image_set.all %}
        {{post_image.image.url}}
    {% endfor %}
{% endfor %}

What am I doing wrong?

Here is my views.py file. views.py

# Create your views here.
def index(request):
    posts=Post.objects.filter(approved=True).order_by('-published_date')
    context = {"posts":posts}
    return render(request, 'post/home.html',context)

Advertisement

Answer

The default related name for a foreign key relational is the name of the model (PostImage) but in your template for loop you called it post_image Following relationships “backward”

change

{% for post_image in post.post_image_set.all %}

into

{% for post_image in post.postimage_set.all %}

Template code (with change)

{% for post in posts %}
    {% for post_image in post.postimage_set.all %}
        {{post_image.image.url}}
    {% endfor %}
{% endfor %}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement