简体   繁体   English

Django模板中的外键关系

[英]Django foreign key relation in template

i know you will say that this question is asked before many times but i havent solved it yet... 我知道你会说很多次都会问这个问题,但我还没有解决它...

models.py models.py

class Doc(UploadModel):
    doc_no =  models.CharField(max_length=100, verbose_name = "No", blank=True)
    date_added = models.DateTimeField(verbose_name="Date", default=datetime.now,
                 editable=False)

class DocImage(models.Model):
    property = models.ForeignKey(Doc, related_name='images')
    image = FileBrowseField("Docs", max_length=200,
            directory="doc_img/%Y/%m/%d/%H/%M/%S/", 
            extensions=[".jpg",".tif"], blank=True, null=True)

views.py views.py

def doc_detail(request, dosc_no):

    res = Doc.objects.filter(doc_no = dosc_no)        
    return render_to_response("doc/doc_detail.html",  {"result": res})

templates: 模板:

{% for i in docimage.property_set.all %}

{{ i.image.url }}  

{% endfor %}

i have tried above template but i didnt get any result. 我试过上面的模板,但我没有得到任何结果。 so i want to get imageurl adress in DocImage class... 所以我想在DocImage课程中获得imageurl地址...

all helps 一切都有帮助

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: 您需要在DocImages类上定义外键,如下所示:

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访问DocImages,例如:

Doc.docimage_set.all()

Docs on Related Objects 相关对象的文档

But setting related_name in the property field lets you do 但是,在属性字段中设置related_name可以实现

Doc.images.all()

Just make sure whatever you pass to the template in the view context matches what is used in the template, eg 只需确保您在视图上下文中传递给模板的内容与模板中使用的内容相匹配,例如

# 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 与Doc相关的图像由doc的images属性检索,该属性是从ForeignKey中的related_name属性生成的

code: 码:

{% for doc in result %}
  {% for docimage in doc.images.all %}
    {{ docimage.image.url }}
  {% endfor %}
{% endfor %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM