About •  Books •  Apps •  Jobs •   Feeds •  Twitter
Login

Useful Django API's

Two useful Django API's that I've found today.

Model to Dict

A useful little fella hiding away in the forms module. Ever want a dictionary of your model and it's fields? Then this one will give you that. Useful for mapping a model into a big string. For example in a recent project we are sending a message about the facility.. pass in a facility into a string and you'll get:

>>> "%(id)s" % facility
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: 'Facility' object is unsubscriptable
But with add in a model_to_dict call and you'll get back a dictionary suitable for mapping:
from django.forms.models import model_to_dict
>>> "%(id)s" % model_to_dict(facility)
'1'

Finding models

This one requires a few assumptions. Supposing you want to find an model called Log in your project. You don't care what the model is, what application it is in, just that there is something called Log. We would presume that Log had all the appropriate API and made sense in the project. 

In my scenario, I need to find the table name of log, so that I can run some custom, raw sql on it. I did not want to hardcode the table name. So I needed to find log, to access the db_table. The class from django.db.models.loading import AppCache provides some very useful stuff.

from django.db.models.loading import AppCache

class _models:
    def __init__(self):
        app = AppCache()
        for m in app.get_models():
            setattr(self, m.__name__, m)

models = _models()

This creates a instance models that contains a pointer to the model definitions. I called this resolve.py, sounded like a reasonable name. So now I can do:>

>>> from resolve import models
>>> models.Log
<class 'apps.sms.models.base.Log'>
And I've got the Log, regardless of where it came from.

Comments

There are no comments.

Login to add comments