Django:获取模型字段列表? [英] Django: Get list of model fields?
问题描述
我已经定义了一个用户
类,最终从 models.Model
继承。我想得到为此模型定义的所有字段的列表。例如, phone_number = CharField(max_length = 20)
。基本上,我想检索从 Field
类继承的任何东西。
I've defined a User
class which (ultimately) inherits from models.Model
. I want to get a list of all the fields defined for this model. For example, phone_number = CharField(max_length=20)
. Basically, I want to retrieve anything that inherits from the Field
class.
我以为我能够通过利用 inspect.getmembers(model)
来检索它们,但是它返回的列表不包含任何这些字段。看起来Django已经掌握了这个类,并添加了所有的魔法属性,并删除了实际定义的内容。那么我怎么能得到这些领域?
I thought I'd be able to retrieve these by taking advantage of inspect.getmembers(model)
, but the list it returns doesn't contain any of these fields. It looks like Django has already gotten a hold of the class and added all its magic attributes and stripped out what's actually been defined. So... how can I get these fields? They probably have a function for retrieving them for their own internal purposes?
推荐答案
对于Django版本1.8及更高版本:
For Django versions 1.8 and later:
get_all_field_names()
方法是已经从Django 1.8开始,并将在1.10中删除。
上面链接的文档页面提供了一个完全向后兼容的 get_all_field_names()
的实现,但是对于大多数目的 [f.name for f in MyModel._meta.get_fields()]
应该可以正常工作。
The documentation page linked above provides a fully backwards-compatible implementation of get_all_field_names()
, but for most purposes [f.name for f in MyModel._meta.get_fields()]
should work just fine.
对于1.8之前的Django版本:
For Django versions before 1.8:
model._meta.get_all_field_names()
应该做的伎俩。
这需要一个实际的模型实例。如果你所有的都是 django.db.models.Model
的子类,那么你应该调用 myproject.myapp.models.MyModel._meta.get_all_field_names ()
That requires an actual model instance. If all you have is a subclass of django.db.models.Model
, then you should call myproject.myapp.models.MyModel._meta.get_all_field_names()
这篇关于Django:获取模型字段列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!