Home > OS >  Django prefetch_related for many to many join not working
Django prefetch_related for many to many join not working

Time:12-10

I have a many to many relation on models.

Product can have many images and image can assign to multiple productions.

this is my model type :

from django.db import models

class Image(models.Model):
    image_id = models.AutoField(primary_key=True)
    image_name = models.TextField(max_length=200)

class Product(models.Model):
    product_id = models.AutoField(primary_key=True)
    product_name = models.TextField(max_length=200)
    image = models.ManyToManyField(Image, related_name="image")

and in view im filling model like this :

    def home(self):
        """Renders the home page."""
        assert isinstance(self, HttpRequest)
    
        all_product = Product.objects.prefetch_related('image').all()

 return render(
        self,
        'app/index.html',
        {
            'all_product': all_product
        }
    )

and in my template if i call model like this :

{% for each_model in all_product %}
   <label> {{each_model.product_id}}</label>
   <label> {{each_model.image.image_id}}</label>
{% endfor %}

only items shows from products not the joined value from manyTomany table.

CodePudding user response:

{% for each_model in all_product %} 
    <label> {{each_model.product_id}}</label>
    {% for image in each_model.image %}
        {{ image.image_id }}
    {% endfor %}
{% endfor %}

As I mentioned in my comment. You should loop over each_model.image and then access the image_id

  • Related