Django:如何通过模板获取外键连接的数据? [英] Django: How to get data connected by ForeignKey via Template?

查看:16
本文介绍了Django:如何通过模板获取外键连接的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几周以来,我一直在学习 Python 和 Django.到目前为止,阅读其他用户的问题和答案已经足够了.但是现在我的第一个问题的时刻已经到来.

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.

我想获取 Image 类的第一个对象的 url,该对象由 ForeignKey 关联到 Gallery,该 Gallery 由 ForeignKey 关联到类 Entry.

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.

到目前为止的models.py:

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')

观点:

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

模板:

{% 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?

问候巴斯蒂安

推荐答案

您可以访问相关成员 就像 模板中的其他属性,所以你可以执行以下操作:item.gallery_set.all.0.image_set.all.0.picture.img.但是,在 BlogEntry 上定义一个查找并返回适当图片的方法可能更容易,这样您就可以执行 item.first_image 或类似的操作

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:如何通过模板获取外键连接的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆