如何从Django模板中的PK获取对象?

问题描述:

在django模板内部,我想使用对象的pk获取对象的名称。例如,假设我有来自类 A 的对象pk,我想执行以下操作:

Inside django template, I would like to get object's name using object's pk. For instance, given that I have pk of object from class A, I would like to do something like the following:

{{ A.objects.get(pk=A_pk).name }}

我该怎么做?

来自Django模板语言

访问方法调用


由于Django有意限制模板语言中可用的逻辑处理量,因此无法将参数传递给从模板内部访问的方法调用。数据应该在视图中计算,然后传递到模板进行显示。

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