我如何循环通过对象的字段?

时间:2012-04-27 15:50:43

标签: python django model

我有这样的模型,我如何循环它而不必输入company.id,company.name等?

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)

4 个答案:

答案 0 :(得分:21)

您可以遍历所有字段名称,如此

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

如果您有类别实例,这也有效:

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)

Django 1.8的更新

Django 1.8现在有一个official model Meta api,您可以轻松抓住所有字段:

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

答案 1 :(得分:7)

视图中的迭代

如果您的实例companyCompany

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

答案 2 :(得分:4)

首先get them,然后使用for循环或列表理解。

答案 3 :(得分:1)

这是一个可能的解决方案:

entity = Company.all().get()

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

另一个可能是:

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