Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template get first?

I need to do something like

{{ article.product.images.first.image.url }}

In my template, but there is no "first" (images is a RelatedManager for which I found very little documentation).

Is there another way to do this? I can get the first model with

{{ article.product.images.get_query_set|first }}

But then I need to dig a few properties deeper, and that doesn't work.


If it helps, my image model looks like this:

class ComponentImage(models.Model):
    component = models.ForeignKey(Component, related_name='images')
    image = models.ImageField(upload_to='uploads')

And article.product is a Component.

like image 607
mpen Avatar asked Dec 14 '22 01:12

mpen


1 Answers

How about {{article.product.images.all.0.image.url}}' ?

This is the same as the python expression article.product.images.all[0].image.url.

Another option is to add a method to the product model that returns images[0].image.url

like image 193
Tom Leys Avatar answered Dec 31 '22 15:12

Tom Leys