[ACCEPTED]-How can I introspect properties and model fields in Django?-models

Accepted answer
Score: 15

If you strictly want just the model fields 6 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 5 only bit that's extra here is running through 4 the class to find the fields that correspond 3 to property descriptors. Accessing them 2 via the class gives the descriptor, whereas 1 via the instance it gives you the values.

Score: 1

The trouble is you say you only want fields, but 13 then complicate things by throwing properties 12 into the mix. There isn't really any easy 11 way in Python of distinguishing between 10 a property and any other random method. This 9 isn't anything to do with Django: it's simply 8 that a property is just a method that is 7 accessed via a descriptor. Because any number 6 of things in the class will also be descriptors, you'll 5 have trouble distinguishing between them.

Is 4 there any reason why you can't define a 3 list at the class level that contains all 2 the properties you want, then just call 1 getattr on each of the elements?

Score: 0

You should use the dir() function on your 3 instance. Skipping whatever starts with 2 '__' and than use getattr to get the value 1 from your instance.

properties = [prop for prop in dir(SomeClass) if not prop.startswith("__")]

obj = {}
for prop in properties:
    obj[prop] = getattr(myinstance, prop)
Score: 0
class Awesome(models.Model):
 foo = models.TextField()
 bar = models.CharField(max_length = 200)

awe = Awesome()
for property in awe.__dict__.copy():
 # pass private properties.
 if not property.startswith('_'):
  print property,getattr(awe,property)

This is how they do it in Django.


More Related questions