Django: Get list of model fields?

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.

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?


For Django versions 1.8 and later:

The get_all_field_names() method is deprecated starting from Django 1.8 and will be removed in 1.10.

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.

For Django versions before 1.8:

model._meta.get_all_field_names()

That should do the trick.

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()


The get_all_related_fields() method mentioned herein has been deprecated in 1.8. From now on it's get_fields() .

>> from django.contrib.auth.models import User
>> User._meta.get_fields()

I find adding this to django models quite helpful:

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

This lets you do:

for field, val in object:
    print field, val
链接地址: http://www.djcxy.com/p/38724.html

上一篇: 为什么DEBUG = False设置让我的django静态文件访问失败?

下一篇: Django:获取模型字段列表?