Django foreign key relation in template

[亡魂溺海] 提交于 2019-11-28 06:53:42
will-hart

If you review the foreign key documentation, if you have a relationship like

Doc -> has many DocImages

you need to define your foreign key on the DocImages class like so:

class DocImage(models.Model):
    property = models.ForeignKey(Doc, related_name='images')

If you don't set related names, you can access the DocImages from the Doc like:

Doc.docimage_set.all()

Docs on Related Objects

But setting related_name in the property field lets you do

Doc.images.all()

Just make sure whatever you pass to the template in the view context matches what is used in the template, e.g.

# in the view
return render_to_response('mytemplate.html', { 'mydoc' : doc, 'mydocimage' : img }

This can then be used in the template as follows:

# 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 }}
  • first you iterate over the result
  • the images related to a Doc are retrieved by the images property of doc which is generated from the related_name attribute in the ForeignKey

code:

{% for doc in result %}
  {% for docimage in doc.images.all %}
    {{ docimage.image.url }}
  {% endfor %}
{% endfor %}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!