Looping over a list of records, Django displays the literal value of each record. But, what if the field is a foreign key? So, here is an example
{% for record in records %}
{{ record.get_fields|dict_key:field }}
{% endfor %}
The dict_key is a template filter that imitates a dictionary get function given the field.
@register.filter(name = 'dict_key')
def dict_key(a_dict, key):
the_key = normalize(key) # lowercases the key
return the_dict.get(the_key, None)
So, if a field is a foreign key in the model, Django will display the foreign key ID. Say, for example, the field is room, Django will show '1' (the foreign key ID for room) for the first record, '2' for the second record, etc. But, I want to know how to generically and programmatically render the value of the foreign key, e.g. 'Kitchen' for the foreign key with ID 1, 'living room' for the foreign key with ID 2, etc.
Any help is appreciated
Edit 1:
The idea is to create a generic template that renders the records based on the type of fields (e.g. currency field to use custom currency filter) in a table. For that to work, I have to loop over the fields
{% for record in records %}
<tr>
{% for field in relevant_fields%}
<td>
{% if field in currency_fields %}
{{ record.get_fields|dict_key:field|currency }}
{% else %}
{% record.get_fields|dict_key:field}}
{% endif %}
</td>
{% endfor %}
{% endfor %}
So, I'm looking up the field name using the get_fields helper method of the model and based on the type of the filed, I am formatting my output. This way, I get to reuse the same table template.