Show only the first image in template in Django

2

I have two models: the first Property model and the second model Property Image:

Class Property(models.model):
    title = models.CharField()


Class PropertyImage(models.model):
    property = modelos.Foreignkey(Property, related_name='images')
    imagen = models.ImageField()

PropertyImage is where the images of the properties are stored and is related to the first model with a foreign key.

I know that to get the url of the first image of a property in a query would do something like this:

p1 = Property.objects.first() # la primera propiedad
p1.images.first() # la primera imagen de la propiedad 1

My question is if the template sent a query where all the properties are (or filtered according to the case) as it would within the template to show only the url of the first image for each property?

I tried to use the first function inside the template but it marks me syntax error.

    
asked by Javier Cárdenas 17.10.2016 в 00:26
source

1 answer

3

You should not add programming logic to templates.

Your best option is to add a property to your model:

Class Property(models.model):
    title = models.CharField()

    @property
    def primera(self):
        return self.image.all()[0]

To show the url inside the Template:

{% for property in properties %}
  <img src="{{ property.primera.image.url }}">
{% endfor %}

Notes :

  • I'm not sure there's a first() function, but [0] returns the first record of a QuerySet .
  

The inverse relationships are used and this is the documentation: link

    
answered by 17.10.2016 / 05:48
source