Django — List all fields in an Object

The last extremely simple post about “How to get the object instance primary key in Django” reminded me of something.

Listing all model fields in a django model instance

for field in model_instance._meta.fields:

model_instance._meta.get_field('field_name') # if you want one field    

Listing all attributes in a python object

Similarly, ever have a random object that you don’t know the fields of?
Or ever not remember whether your field/method/attribute was called short_description or shortdescription?

Use the built in dir() function.


6 thoughts on “Django — List all fields in an Object

  1. Better to access the names via the Model meta options: [ for f in model_or_instance._meta.fields]

    As a secondary hint, if you just need to “get” one field instance, you can use ._meta.get_field(‘field_name’)

  2. This was really cool stuff.. I was looking to update the list_display dynamically… Wow, then i found this post.. gr8 n thanks….

  3. This it’s good but, if we have a ManyToManyField on model then _meta.fields() doesn’t get it.

    Does anyone know how get that field too ?

    I have some tricks but don’t work really well: _meta._many_to_many()


  4. Try mode_instance._meta.get_all_field_names(). You’ll need to filter out ‘id’, but it includes many-to-many fields and saves you the step of having to look up the name out of the field object.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s