15

Since a few weeks I am learning Python and Django. Up to this point it has been enough to read the questions and the answers of other users.But now the moment of my first own question has come.

I will try to describe my problem as best i can. My problem is that I cant query or get the data I want.

I want to get the url of the first object of class Image which is associated by ForeignKey to a Gallery, which is associated by ForeignKey to the class Entry.

Here the models.py so far:

class BlogEntry(models.Model):
   ...
   title = models.CharField(max_length=100)
   ...

class Gallery(models.Model):
   entry = models.ForeignKey('BlogEntry')

class Image(models.Model):
  gallery = models.ForeignKey('Gallery')
  picture = models.ImageField(upload_to='img')

The View:

def view(request):
  return render_to_response('mainview.html', {
    'entryquery': BlogEntry.objects.all(),
    }
)

The Template:

{% for item in entryquery %}
  <h1>{{ item.title }}</h1>
  <img src="{{ item.WHAT TO ENTER HERE? :) }}" />
{% endfor %}

It is clear what I want? Could somebody help me and when possible write a short explanation?

greetings Bastian

cberner
  • 3,000
  • 3
  • 22
  • 34
user1459531
  • 153
  • 1
  • 1
  • 4

2 Answers2

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

cberner
  • 3,000
  • 3
  • 22
  • 34
  • Thanks a lot for your quick answer :) . I do not understand exactly this line of code. Could you give me a link to a documentation of the access to related members? I did no find something on the Django documentation page. – user1459531 Jun 15 '12 at 19:32
  • Yep, added a link to it. Hope that helps! – cberner Jun 15 '12 at 19:35
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 %}
Gustavo Morales
  • 2,614
  • 9
  • 29
  • 37
Dimitris Kougioumtzis
  • 2,339
  • 1
  • 25
  • 36