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:
    print field.name

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.

dir(model_instance)

6 Comments

  1. SmileyChris says:

    Better to access the names via the Model meta options: [f.name 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. Senthilkumaran says:

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

  3. ecairo says:

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

    regards

    1. Kshitiz says:

      Thanks….that _meta._many_to_many() worked … !!!

  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.

  5. You can also use django.forms.models.model_to_dict and call .keys() on the result.

Leave a Comment