djangodjango-modelsdjango-shell

Get all fields of a model in Django Shell


Is it possible to output names of all fields of a specific model in Django Shell? For example, how to get fields from User model:

>>> from django.contrib.auth.models import User

I know I can get it by accessing models.py of the appropriate app but it would be more convenient for me to get information on models of all the apps at the same place.


Solution

  • To return a list of field objects of the User model. Use:

    field_names = User._meta.get_fields()
    

    To return a list of field names for User model, Use:

    field_names = [f.name for f in User._meta.get_fields()]