Substitute a model's key name for rendering a template?

Hi folks,

I have a template that is meant for showing different query results. The first results are alwyas the same:

{% for result in results %}
  {{ result.last_name }}
  {{ result.first_name }}
  .
  .
  .
{% endfor %}

the . represent a variable number of additional data fetched from different models.

Is there a way to substitute the key names of a model before rendering, so that (for example)

{{ result.birthday }}                 -referring to the "birthday" key of the model ( of course)

is substituted by another term…call it “key1” and one can show the same in template by using

{{ result.key1 }}

instead?

p.s. without altering the model itself, of course :wink:

You can use property within Model like this


class ABC(Model):
    birthday = models.CharField(max_length=30)

    @property
    def birthday_alternate_key(self):
        return self.birthday

and then you can use birthday_alternate_key this key within template.

1 Like

Review the docs for template variables

In a variable reference of the form {{ object.attribute }}, object is a reference to a key in the context dict supplied to the rendering engine.
Attribute can be an attribute of that object, or it can be a key if object is a dict.

So in addition to @addwebsolution 's idea above, you can also build a dict in your view where you’re “normalizing” the fields to standard names to be used by templates, or you could annotate your query to add a field to your result set with the name to be used in the template.

2 Likes