How do I go through the fields of an object?

I have such a model as I can skip it, and I do not need to type 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) 
+7
source share
4 answers

Get them first, then use a loop or list comprehension.

+3
source

You can iterate over all field names, for example

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

this also works if you have an instance of the category:

 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 Meta api model

+20
source

Iteration in view :

If you have an instance of company of company :

 fields= company.__dict__ for field, value in fields.items(): print field, value 
+3
source

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 may be:

 # this returns a dict with the property # name as key and the property val as its value entity.__dict__.get('_entity') 
+1
source

All Articles