Access ForeignKey set directly in template in Django

后端 未结 5 2105
南方客
南方客 2020-12-13 02:43

I have this simplified model:

class Item(models.Model):
    name = models.CharField(max_length=120)

class ItemImage(models.Model):
    image = models.ImageF         


        
5条回答
  •  执念已碎
    2020-12-13 03:15

    Or you could add a method to your Item model:

    def get_first_image(self):
        return self.itemimage_set.all()[0]
    

    and then call this method in your template:

    {{ item.get_first_image }}
    

    Or you could use:

    {{ item.itemimage_set.all.0 }}
    

    and to get the first image's url:

    
    

    Though if you need more flexibility (more than one picture in certain cases, etc.) it's probably best to write a little templatetag.

提交回复
热议问题