Django: Get list of model fields?

Django versions 1.8 and later:

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.


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


As most of answers are outdated I'll try to update you on Django 2.2 Here posts- your app (posts, blog, shop, etc.)

1) From model link: https://docs.djangoproject.com/en/stable/ref/models/meta/

from posts.model import BlogPost

all_fields = BlogPost._meta.fields
#or
all_fields = BlogPost._meta.get_fields()

Note that:

all_fields=BlogPost._meta.get_fields()

Will also get some relationships, which, for ex: you can not display in a view.
As in my case:

Organisation._meta.fields
(<django.db.models.fields.AutoField: id>, <django.db.models.fields.DateField: created>...

and

Organisation._meta.get_fields()
(<ManyToOneRel: crm.activity>, <django.db.models.fields.AutoField: id>, <django.db.models.fields.DateField: created>...

2) From instance

from posts.model import BlogPost

bp = BlogPost()
all_fields = bp._meta.fields

3) From parent model

Let's suppose that we have Post as the parent model and you want to see all the fields in a list, and have the parent fields to be read-only in Edit mode.

from django.contrib import admin
from posts.model import BlogPost 

@admin.register(BlogPost)
class BlogPost(admin.ModelAdmin):
    all_fields = [f.name for f in Organisation._meta.fields]
    parent_fields = BlogPost.get_deferred_fields(BlogPost)

    list_display = all_fields
    read_only = parent_fields