Home > Mobile >  Why i cant get the prefetched related object in DJANGO?
Why i cant get the prefetched related object in DJANGO?

Time:03-19

I want to get the midia with the thumbnail = True for every galeria using the prefetch related.

class Midia(Base): 
    galeria = models.ForeignKey(Galeria, on_delete=models.CASCADE, related_name= "midias")        
    thumbnail = models.BooleanField('Thumbnail ', default=False)
    video_thumbnail = models.URLField(blank = True)
    imagem = StdImageField(upload_to='midias/', blank=True, delete_orphans=True)

class Galeria(Base): 
    titulo = models.CharField('Título', max_length=100) 
    descricao = models.TextField('Descrição', blank= True)  

I did it using this code in the view:

 galerias = Galeria.objects.prefetch_related(Prefetch('midias', queryset= Midia.objects.filter(thumbnail = True))).all() 

And this in the HTML:

 {% for galeria in galerias %}  
     {% with thumbnail=galeria.midias.first %} 
         {% if thumbnail %}
             {% if thumbnail.imagem %}
                 <img src="{{ thumbnail.imagem.url }}" alt="" > 
             {% else %} 
                 <img src="{{ thumbnail.video_thumbnail }}" alt=""> 
             {% endif %}   
         {% else %} 
              <img src="generic image" alt="" > 
         {% endif %}
      {% endwith %} 

But why when i try to do this:

{% with thumbnail=galeria.midias %}

It returns None. Checking the sqls hits in the database the galeria.midias.first does not appear (the prefetch is working and returning only the midia with the thumbnail = True). Why when i use galeria.midias it returns None?

CodePudding user response:

Because midias is a queryset. Not an object. So you have to iterate through it.

{% for galeria in galerias %}  
 {% for thumbnail in galeria.midias.all %}
     {% if thumbnail %}
         {% if thumbnail.imagem %}
             <img src="{{ thumbnail.imagem.url }}" alt="" > 
         {% else %} 
             <img src="{{ thumbnail.video_thumbnail }}" alt=""> 
         {% endif %}   
     {% else %} 
          <img src="generic image" alt="" > 
     {% endif %}
  {% endfor %}
{% endfor %}
  • Related