Menu Close

How to get a model’s fields in Python Django?

To get a model’s fields in Python Django, we can use the get_fields method.

For instance, we write

from django.contrib.auth.models import User

[field.name for field in User._meta.get_fields()]

to call User._meta.get_fields() to return the field names of the fields in the User model with

[field.name for field in User._meta.get_fields()]

field.name has the name for each field.

Posted in Python, Python Answers