how do i loop through fields of an object?


Question

I have a model like this, how can I loop through it and not have to type out company.id, company.name, etc?

class Company(models.Model):
    name = models.CharField(max_length=1000)
    website = models.CharField(max_length=1000)
    email = models.CharField(max_length=200)
    phone_number = models.CharField(max_length=100)
    city = models.CharField(max_length=1000)
    zip = models.IntegerField()
    state = models.CharField(max_length=1000)
    address = models.CharField(max_length=1000)
    address2 = models.CharField(max_length=1000)
1
10
4/27/2012 3:51:34 PM

Accepted Answer

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

4
5/23/2017 12:18:10 PM

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 User
for field in User._meta.get_fields():
    print field

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon