2013-02-19 134 views
1

我学习Django ORM。如何在我的模板中获得照片Django外键。在模板中访问

def index(request):  
    animal = Animal.objects.all() 
    return render_to_response('animal.html', 
           {'animal':animal,}, 
           context_instance=RequestContext(request)) 

模板:

{{ animal.name }} 
{{ animal.photo.all }} 

但这不工作。

型号:

class Animal(models.Model): 
    name = models.CharField(max_length=255) 

class Photo(models.Model): 
    photo = models.ImageField(upload_to='media/images') 
    animal = models.ForeignKey(Animal) 

回答

4

你需要阅读following relationships的文档,看你怎么访问相关项目。

在你的情况下,每个animal有一个photo_set这是一种获取属于该动物的所有照片对象列表的方式。

在模板中,你会怎么做:

{{ animal.name }} 
{% for picture in animal.photo_set.all %} 
    <img src="{{ picture.photo.url }}" /> 
{% endfor %}