22👍
✅
You can access related members just like other attributes in a template, so you can do something like: item.gallery_set.all.0.image_set.all.0.picture.img
. However, it might be easier to define a method on BlogEntry that looked up and returned the appropriate picture, so that you could just do item.first_image
or something like that
3👍
class BlogEntry(models.Model):
...
title = models.CharField(max_length=100)
...
class Gallery(models.Model):
entry = models.ForeignKey('BlogEntry',related_name="galleries")
class Image(models.Model):
gallery = models.ForeignKey('Gallery',related_name='images')
picture = models.ImageField(upload_to='img')
You have to add related_name in foreign key in gallery model and in template view:
{% for g in blogentry.galleries.all %}
{{g.name}}
{%for i in g.images.all %}
<img src="{{i.picture.url}}">{{i.picture}}</img>
{% endfor %}
{% endfor %}
- Pagination and get parameters
- What is the difference between a Multi-table inherited model and a simple One-to-one relationship between the same two models?
Source:stackexchange.com