Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I introspect properties and model fields in Django?

I am trying to get a list of all existing model fields and properties for a given object. Is there a clean way to instrospect an object so that I can get a dict of fields and properties.

class MyModel(Model)
    url = models.TextField()

    def _get_location(self):
        return "%s/jobs/%d"%(url, self.id)

    location = property(_get_location)

What I want is something that returns a dict that looks like this:

{
  'id' : 1,
  'url':'http://foo',
  'location' : 'http://foo/jobs/1'
}   

I can use model._meta.fields to get the model fields, but this doesn't give me things that are properties but not real DB fields.

like image 443
shreddd Avatar asked Feb 08 '11 07:02

shreddd


1 Answers

If you strictly want just the model fields and properties (those declared using property) then:

def get_fields_and_properties(model, instance):
    field_names = [f.name for f in model._meta.fields]
    property_names = [name for name in dir(model) if isinstance(getattr(model, name), property)]
    return dict((name, getattr(instance, name)) for name in field_names + property_names)

instance = MyModel()
print get_fields_and_properties(MyModel, instance)

The only bit that's extra here is running through the class to find the fields that correspond to property descriptors. Accessing them via the class gives the descriptor, whereas via the instance it gives you the values.

like image 103
John Montgomery Avatar answered Oct 04 '22 17:10

John Montgomery