Get/List model fields

Posted: February 22nd, 2010 | Author: Davo | Filed under: Django | Tags: , , , , , | 4 Comments »

It is possible to get/list all of the fields for the given model, to do so you need to access the _meta attribute of the Model.
The following example demonstrates how to do it.


# in the models.py
class Car(models.Model)
    year = models.IntegerField()
    name = models.CharField(max_length=50)
    ...

    def get_fields(self):
        # make a list of field/values.
        return [(field, field.value_to_string(self)) for field in Car._meta.fields]

Now that we implemented the get_fields function for our Car model, we can use this in the template…

# your template file...
# I assume that the variable 'car' is an instance of Car object.
{% for field, value in car.get_fields %}
    {{ field }} : {{ value }}
{% endfor %}