在 django 模板中,我想使用对象的 pk 获取对象的名称。例如,假设我有来自 A
类的对象 pk,我想执行如下操作:
{{ A.objects.get(pk=A_pk).name }}
我该怎么做?
最佳答案
来自 The Django Template Language 上的文档:
Because Django intentionally limits the amount of logic processing available in the template language, it is not possible to pass arguments to method calls accessed from within templates. Data should be calculated in views, then passed to templates for display.
所以你看,你应该在你的 views.py 中计算这个:
def my_view(request, A_pk):
...
a = A.objects.get(pk=A_pk)
...
return render_to_response('myapp/mytemplate.html', {'a': a})
在你的模板中:
{{ a.name }}
{{ a.some_field }}
{{ a.some_other_field }}
关于python - 如何从 Django 模板中的 PK 获取对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13866952/