Django — List all fields in an Object

by Yuji

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)
About these ads