Maddie Graham
Maddie Graham

Reputation: 2177

Receiving a list of related models from the list of objects (bound by a foreign key). Django

I have two very simple classes for products and photos. I would like to present products on the main page of my store along with photos related to a foreign key. But I do not know how to do this, I found many answers to get this in the view using a join like 'prefetch_related' but my ID changes for each case. So how do you present your photos for each product? are there any Django tags about which I do not know?

my models.py

class Product(models.Model)
    name = models.CharField(max_length=10)

class Image(models.Model)
    image = models.ImageField()
    name_related = models.ForeignKay(Product, on_delate=models.CASCADE)

views.py

def home(request):
    product_list = Product.objects.all()[:12]
    #img = ??
    context = {'product_list': product_list,
               }
    return render(request, 'home.html', context)

home.html

{% for product in product_list %}
{{ product.name }}
<!-- {{ product.imge }} ' element presenting the first photo for each 'product' model'???-->
{% endfor %}

Any help will be appreciated.

Upvotes: 1

Views: 25

Answers (2)

Sergey Pugach
Sergey Pugach

Reputation: 5669

Just do

{% for product in product_list %}
    {{ product.name }}
    {% for image in product.image.all %} 
        <!-- {{ image.image.url }} -->?
    {% endfor %}
{% endfor %}

Upvotes: 1

coler-j
coler-j

Reputation: 2149

Since a foreign relation has been established you can iterate through the related models from the parent model.

The related models are already accessible from the parent model without doing anything explicit.

In your template you can do this:

{% for product in product_list %}
    {{ product.name }}
    {% for product_image in product.image.all %}
        <!-- Iterate through this products related images -->
        {{ product_image.image.url }}
    {% endfor %}
{% endfor %}

For performance reasons, you will want to prefetch the relations, or else for every product you will do an additional query, so, in your view you will want to add this:

product_list = Product.objects.all().prefetch_related('image')[:12]

Upvotes: 1

Related Questions