brsbilgic
brsbilgic

Reputation: 11833

Django getting properties of model dynamically

I have a model like

class Document(models.Model):
    comment = models.TextField(null=True,blank=True)
    upload_date = models.DateTimeField(blank=False)

Document objects are listed in a template as

{% for doc in doc_list %}
    {{ doc.comment }}
    {{ doc.upload_date }}
{% endfor %}

However, I'd like to reach the properties of doc dynamically like

{{ doc."comment" }}

or

{{ doc|getField:"comment" }}

How can I do that?

Thanks

Upvotes: 0

Views: 162

Answers (1)

Dan Breen
Dan Breen

Reputation: 12924

I assume you mean you want to access fields on a model by using another variable, which you don't necessarily know at the time. So you might have some_var be passed into the template, and this is the field in the model that you'd like to display, such as comment or upload_date.

You could build a template tag to do this:

@register.simple_tag
def get_model_attr(instance, key):
    return getattr(instance, key)

Now in your template you can do stuff like:

{% for doc in doc_list %}
    {% get_model_attr doc "comment" %}
    {% get_model_attr doc some_var %}
{% endfor %}

Upvotes: 2

Related Questions