我已经定义了一个User类,它(最终)继承自models.Model。我想获得为这个模型定义的所有字段的列表。例如,phone_number = CharField(max_length=20)。基本上,我想检索从Field类继承的任何东西。

我认为我可以利用inspect.getmembers(model)来检索这些字段,但是它返回的列表不包含这些字段中的任何一个。看起来Django已经掌握了这个类,添加了它所有神奇的属性,并去掉了实际定义的内容。所以…我怎样才能得到这些田地?他们可能有一个功能来检索他们自己的内部目的?


当前回答

不清楚您拥有的是类的实例还是类本身,并试图检索字段,但无论哪种方式,考虑以下代码

使用实例

instance = User.objects.get(username="foo")
instance.__dict__ # returns a dictionary with all fields and their values
instance.__dict__.keys() # returns a dictionary with all fields
list(instance.__dict__.keys()) # returns list with all fields

使用类

User._meta.__dict__.get("fields") # returns the fields

# to get the field names consider looping over the fields and calling __str__()
for field in User._meta.__dict__.get("fields"):
    field.__str__() # e.g. 'auth.User.id'

其他回答

未被别人提及的细节:

[f.name for f in MyModel._meta.get_fields()]

比如Get

['id', 'name', 'occupation']

and

[f.get_attname() for f in MyModel._meta.get_fields()]

get

['id', 'name', 'occupation_id']

If

reg = MyModel.objects.first()

then

reg.occupation

比如Get

<Occupation: Dev>

and

reg.occupation_id

get

1

只是补充,我使用self对象,这为我工作:

[f.name for f in self.model._meta.get_fields()]

我发现把这个添加到django模型中非常有用:

def __iter__(self):
    for field_name in self._meta.get_all_field_names():
        value = getattr(self, field_name, None)
        yield (field_name, value)

这让你做:

for field, val in object:
    print field, val
def __iter__(self):
    field_names = [f.name for f in self._meta.fields]
    for field_name in field_names:
        value = getattr(self, field_name, None)
        yield (field_name, value)

这在django==1.11.8中对我有效

不清楚您拥有的是类的实例还是类本身,并试图检索字段,但无论哪种方式,考虑以下代码

使用实例

instance = User.objects.get(username="foo")
instance.__dict__ # returns a dictionary with all fields and their values
instance.__dict__.keys() # returns a dictionary with all fields
list(instance.__dict__.keys()) # returns list with all fields

使用类

User._meta.__dict__.get("fields") # returns the fields

# to get the field names consider looping over the fields and calling __str__()
for field in User._meta.__dict__.get("fields"):
    field.__str__() # e.g. 'auth.User.id'