我已经定义了一个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'

其他回答

这很管用。我只在Django 1.7中测试它。

your_fields = YourModel._meta.local_fields
your_field_names = [f.name for f in your_fields]

Model._meta。Local_fields不包含多对多字段。您应该使用Model._meta.local_many_to_many来获取它们。

所以在我找到这篇文章之前,我成功地找到了这个方法。

Model._meta.fields

它的工作原理和

Model._meta.get_fields()

我不确定结果有什么不同,如果有的话。我运行了这个循环,得到了相同的输出。

for field in Model._meta.fields:
    print(field.name)

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

使用实例

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

MyModel._meta.get_all_field_names()在之前的几个版本中被弃用,并在Django 1.10中被移除。

以下是文档中向后兼容的建议:

from itertools import chain

list(set(chain.from_iterable(
    (field.name, field.attname) if hasattr(field, 'attname') else (field.name,)
    for field in MyModel._meta.get_fields()
    # For complete backwards compatibility, you may want to exclude
    # GenericForeignKey from the results.
    if not (field.many_to_one and field.related_model is None)
)))