Django的:如何获取由ForeignKey通过模板连接的数据? [英] Django: How to get data connected by ForeignKey via Template?
问题描述
我会尽力尽我所能描述我的问题。我的问题是,我不能查询或获取我想要的数据。
我想获得由ForeignKey关联的类Image的第一个对象的URL到一个Gallery,它由ForeignKey关联到Entry类。
到目前为止,models.py:
类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')
查看:
def view(request):
return render_to_response('mainview.html',{$ b $'entryquery':BlogEntry.objects.all(),
$ p
{%for item in entryquery%}
< h1> {{item.title}}< / h1>
< img src ={{item.WHAT TO ENTER HERE?:)}}/>
{%endfor%}
很清楚我想要什么?
有人可以帮我,在可能的时候写一个简短的解释吗?
$ b $问候
Bastian
解决方案您可以像访问相关成员一样模板中的其他属性,因此您可以执行如下操作: item.gallery_set.all.0.image_set.all.0.picture.img
。然而,在BlogEntry上定义一个方法可能会更容易,该方法查找并返回相应的图片,以便您可以执行 item.first_image
或类似的东西
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
解决方案 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
这篇关于Django的:如何获取由ForeignKey通过模板连接的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!