In the Lifestream service I’ve been working on, I presented myself with the need to have some class abstraction, but not in the fashion which is available in Django models. I wanted to achieve a base class, which is stored in the database, and then child classes which simply override some methods. It turned out this would be a lot more complex than anticipated.
This is a fairly common approach to class abstraction, especially in Python. It’s used all over the place in your daily code. Whether you are overriding the save() method on your model, or creating your own admin form by subclassing ModelAdmin. I wanted to accomplish a similar task, but doing so on a model. Let’s call it backwards abstraction (since abstraction works the other direction in Django). We create a single table, which houses many classes, and possibly even some denormalization for additional data on these classes.
1 2 3 4 5 6 7 8 9 10 11 12 | |
plugin field which is the name of the class which is extending the instance, and an options field for storing some extra information based on that class. There is also a render() method for the extension which should be handled by the subclass.
1 2 3 | |
TwitterExtension extends from the FeedExtension, which is where we are handling most of the logic.
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 | |
To do this I created a class which I’ve randomly described as TemplateModel. It does exactly what is talked about above. It stores references to each child class within the parent, and upon instantiation, if it can, it returns the child class instead of the parent.
So without further delay, view the source for TemplateModel.
I’d be interested in hearing if anyone else has come up with their own solutions, and if you use something like this in your project how well its working for you.