模板中的Django外键关系 [英] Django foreign key relation in template

查看:24
本文介绍了模板中的Django外键关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道你会说这个问题以前被问过很多次但我还没有解决它...

i know you will say that this question is asked before many times but i havent solved it yet...

模型.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

def doc_detail(request, dosc_no):

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

模板:

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

{{ i.image.url }}  

{% endfor %}

我已经尝试过上述模板,但没有得到任何结果.所以我想在 DocImage 类中获取 imageurl 地址...

i have tried above template but i didnt get any result. so i want to get imageurl adress in DocImage class...

所有帮助

推荐答案

如果您查看 外键文档,如果你有这样的关系

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

Doc -> has many DocImages

您需要像这样在 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')

如果不设置相关名称,可以像这样从Doc访问DocImages:

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

Doc.docimage_set.all()

关于相关对象的文档

但是在属性字段中设置 related_name 可以让您做到

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 }}

这篇关于模板中的Django外键关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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