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?
You should use get_fields()
:
[f.name for f in MyModel._meta.get_fields()]
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 the previous example should work just fine.
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()