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 %}

4 Comments on “Get/List model fields”

  1. 1 Tony Middleton said at 2:16 pm on October 9th, 2010:

    Should line 9 be:

    return [(field.name, field.value_to_string(self)) for field in Car._meta.fields]

  2. 2 StefanNch said at 1:07 am on January 20th, 2011:

    This is very nice!.. Clean and simple!

    Line 9 should be anything you need; instead of ‘field’ or ‘field.name’, you could use ‘field.verbose_name’ etc etc

    But for the purpose of this tip, i believe the author’s example is best!

  3. 3 arsl said at 9:55 am on January 26th, 2011:

    good.. but what about encrypted field??
    for example password.

  4. 4 mike_papa said at 2:57 am on March 10th, 2011:

    I can’t really get it to work. It deosn’t give me any errors, but it seems not to return anything.


Leave a Reply