11

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)
miku
  • 172,072
  • 46
  • 300
  • 307
iCodeLikeImDrunk
  • 16,174
  • 34
  • 103
  • 164
  • To do what? Assign to them? Use them? – Gareth Latty Apr 27 '12 at 15:51
  • possible duplicate of [Django - Iterate over model instance field names and values in template](http://stackoverflow.com/questions/2170228/django-iterate-over-model-instance-field-names-and-values-in-template) – miku Apr 27 '12 at 15:52

4 Answers4

24

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
randlet
  • 3,468
  • 1
  • 15
  • 21
8

Iteration in a view:

If you have an instance company of Company:

fields= company.__dict__
for field, value in fields.items():
    print field, value
rom
  • 3,444
  • 6
  • 38
  • 67
  • Excellent! How would I remove specific tuples from the dict_items list that `__dict__.items()` generates? – Mitsakos May 16 '18 at 16:29
5

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

Community
  • 1
  • 1
Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325
1

this is a possible solution:

entity = Company.all().get()

for propname, prop in entity.properties().items():   
    print propname, prop.get_value_for_datastore(entity)

another one could be:

# this returns a dict with the property 
# name as key and the property val as its value
entity.__dict__.get('_entity') 
aschmid00
  • 6,938
  • 2
  • 45
  • 66