Tuesday, June 4, 2013

Introspecting Django Models

कभी न कभी सभी को अपने गिरेबान में झांकना ही पड़ता है।
(Everyone is forced to look into their own affairs one day.)

We developers like to call it introspection. As if we are going to find something other than what we typed in ourselves! Thoreau went to a jungle to introspect. I am sure he was looking for a Python. Introspecting with Python is fun.

Anyway, it so happens that the simple matter of serializing JSON data to JSON was stuck on the matter of field instance vs field value. When you declare a field on a Django model and then create an instance of that model and do the following:

class DemoModel(models.Model):
    title = models.CharField(max_length=255)

model = DemoModel({'title': 'Introspecting'})
getattr(model, 'title') # 'introspecting'

You get the value of the field that it now holds.

But what if you need to access the methods and attributes of the CharField class. For that you need the instance of the CharField class. You can get that through the _meta attr on the model like this:

fld = model._meta.get_field('title')

# Now you can access the settings done on the class
getattr(fld, 'max_length') # prints 255

There are a bunch of other methods available that let you introspect everything from simple fields to foreign keys and many to many relations.

So now we can introspect from the comforts of our homes. No need to head out to woods.

No comments:

Post a Comment