Django:如何在模板中获取命名的相关字段 [英] Django: How to get a named related field in a template
问题描述
我有一个Django应用,主要模型为Bugs.
I have a Django app where the main model is Bugs.
我有另一个名为Scrub的模型,其中有一个指向Bugs模型的FK.
I have a second Model called Scrub, that has a FK pointing to the Bugs model.
class Scrub(models.Model):
bug_id = models.ForeignKey(Bugs,related_name='scrublines')
user = models.ForeignKey(User)
time = models.DateTimeField()
field = models.CharField(max_length=50)
value = models.CharField(max_length=255)
def __unicode__(self):
return str(self.bug_id)
从外壳中,我可以添加新的Scrub条目.
From the shell, I can add new Scrub entries,.
>>> B = Bugs.objects.get(bug_id=66045)
>>> U = User.objects.get(pk=2)
>>> B.scrublines.create(user=U,time=datetime.datetime.now(),field="field1",value='value1')
<Scrub: 66045>
>>> B.scrublines.create(user=U,time=datetime.datetime.now(),field="field2",value='value2')
<Scrub: 66045>
>>> B.scrublines.create(user=U,time=datetime.datetime.now(),field="field3",value='value3')
<Scrub: 66045>
我可以遍历所有字段并进行迭代
I can walk through all of the fields by getting all, and iterating
>>> lines = B.scrublines.all()
>>> for line in lines:
... print("%s:%s" % (line.field,line.value))
...
field1:value1
field2:value2
field3:value3
我要从模板中执行的操作是通过指定字段名称来获得特定的相关行.我可以从外壳上得到
What I want to do from the template, is get a specific related line, by specifying the field name. I can get that from the shell
>>> B.scrublines.get(field='field1').value
u'value1'
模板遍历了所有错误,并将每个字段放入不同的表格单元格中,我想将field1,field2,field3中的值直接添加到单元格中.
The template walks through all of the bugs, and places each field into a different table cell, and I want to add the value from field1, field2, field3 directly into the cells.
{% for bug in bugs %}
<tr class="bugrow" >
<td>{{bug.bug_id}}</td>
我可以通过在模板中指定字段名称来获得相关行吗?
Can I get a related line by specifying the field name in the template?
推荐答案
在Django模板语言中,点符号可以是字典查找.例如. {{foo.bar}}
将被视为 foo ['bar']
.
In the Django template language, the dot notation can be a dictionary lookup. E.g. {{ foo.bar }}
will be treated as foo['bar']
.
使用Python,我们可以将其转换为各种函数调用...
Using Python we can transform this into a function call of sorts...
class MyGetter(object):
def __getitem__(self, item):
return "Trying to get {}".format(item)
def home(req):
return render(req, "hello.html", {"stuff": MyGetter()})
在 hello.html
中,如果您有类似这样的内容:
And in hello.html
, if you have something like this:
<p>{{ stuff.foo }}</p>
您将在页面上看到消息正在尝试获取foo".基本上,您需要做的就是修改 __ getitem __
的主体以适合您的目的.(并且,当然,为所有内容都提供适当的名称.)
You'll see the message "Trying to get foo" appear on the page. Basically all you need to do is modify the body of __getitem__
to suit your purposes. (And, of course, come up with appropriate names for everything.)
还有其他方法可以做到这一点(即 __ getattr __
),但是我认为使用 __ getitem __
最清楚.
There are other ways to do this (i.e. __getattr__
) but I think using __getitem__
is the most clear.
此外,如果愿意,您还可以 使用自定义模板标签/模板过滤器.这一切都取决于你.我将这样做,因为它似乎涉及最少的运动部件.
Furthermore, you could also use custom template tags/template filters if you like. It's all up to you. This is how I would do it, since it seems to involve the fewest number of moving parts.
尝试一下:
class FieldReader(object):
def __init__(self, bug):
self.__bug = bug
def __getitem__(self, item):
return self.__bug.scrublines.get(field=item).value
您可以在模板中使用
{{ field_reader.field1 }}
获取您发送给 FieldReader
构造函数的任何 Bug
的 field1
的值.
to get the value of field1
for whatever Bug
you sent to the FieldReader
constructor.
这篇关于Django:如何在模板中获取命名的相关字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!