how do i loop through fields of an object? how do i loop through fields of an object? django django

how do i loop through fields of an object?


You can loop over all field names like so

for name in Company._meta.get_all_field_names():    print name

this also works if you have a category instance:

c = Company(name="foo",website="bar",email="baz@qux.com",....,)c.save()for field in c._meta.get_all_field_names():    print getattr(c, field, None)

Update for Django 1.8

Django 1.8 now has an official model Meta api and you can easily grab all the fields:

from django.contrib.auth.models import Userfor field in User._meta.get_fields():    print field


Iteration in a view:

If you have an instance company of Company:

fields= company.__dict__for field, value in fields.items():    print field, value


First get them, then use a for loop or list comprehension.