如果您查看外键文档,如果您有类似的关系
Doc -> has many DocImages
您需要像这样在DocImages类上定义外键:
class DocImage(models.Model): property = models.ForeignKey(Doc, related_name='images')
如果您未设置相关名称,则可以像下面这样从Doc访问DocImage:
Doc.docimage_set.all()
有关对象的文档
但是
related_name在属性字段中进行设置可以
Doc.images.all()
只要确保您在视图上下文中传递给模板的任何内容都与模板中使用的内容匹配,例如
# in the viewreturn render_to_response('mytemplate.html', { 'mydoc' : doc, 'mydocimage' : img }然后可以在模板中使用它,如下所示:
# and in your template to get the images attached to the document{% for i in mydoc.images.all %} ...{% endfor %}# or to get the document the image belongs to{{ mydocimage.property.date_added }}


