[英]how do i loop through fields of an object?
I have a model like this, how can I loop through it and not have to type out company.id, company.name, etc? 我有这样的模型,我如何循环它而不必输入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)
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的更新
Django 1.8 now has an official model Meta api and you can easily grab all the fields: Django 1.8现在有一个官方模型Meta api ,你可以轻松获取所有字段:
from django.contrib.auth.models import User
for field in User._meta.get_fields():
print field
Iteration in a view : 在视图中迭代:
If you have an instance company
of Company
: 如果您有
company
的实例Company
:
fields= company.__dict__
for field, value in fields.items():
print field, value
首先得到它们 ,然后使用for循环或列表理解。
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.