How to get object from PK inside Django template?

前端 未结 5 1688
逝去的感伤
逝去的感伤 2021-02-07 10:38

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 somethi

5条回答
  •  别跟我提以往
    2021-02-07 11:05

    You can add your own tag if you want to. Like this:

    from django import template
    register = template.Library()
    
    @register.simple_tag
    def get_obj(pk, attr):
        obj = getattr(A.objects.get(pk=int(pk)), attr)
        return obj
    

    Then load tag in your template

    {% load get_obj from your_module %}
    

    and use it

    {% get_obj "A_pk" "name" %}
    

提交回复
热议问题