Saturday, September 11, 2010

Overriding individual models in an app without forking

Oops my previous post got hard-wrapped by safari's textarea. :( Here it is again. (I'm assuming moderator is going to prevent me from double posting).

--- 

I was reading about how django's apps' models can't be easily overridden. - e.g http://www.scribd.com/doc/37113340/Why-Django-Sucks-and-How-we-Can-Fix-it

So I was looking at this new app I was making, a CMS for online shops, and thought of a way for users of my app to override individual models in my app without forking.

I want to ask, how does it look? Would it be "bad practice"? How else could I enable user to override individual models?

It uses django-nonrel version of django so the code might be a bit weird to some. I think it works the same for normal django, though.

abstract.py - "Normal Model Code"
http://pastebin.com/C9FFJJK8

This file has a bunch of the models I would have had anyway if I didn't enable model overriding. i.e 'Setting', 'Country', 'Product',
'UserProfile', 'Category', 'Promotion', 'Cart', 'PaymentMethod', 'Order' and 'Item'

models.py - "The 'Magic' Code"
http://pastebin.com/ezhPA6uJ
This file contains an "override_models" method. Use it like "override_models(Country=MyCountry)" whereever... e.g in your models.py, where MyCountry is has a strict is-a relationship with the Country model in abstract.py, meaning they must have at least all the fields and all the relationships of the original model, though more can be added.

It also contains some lazy many to many links. I used appengine so I couldn't use django's many_to_many.

management.py - "Example Usage Code"
http://pastebin.com/jK3vzMt7
(I was just using management.py to do random testing... )

Note my new custom model have new fields... "parent" and "test".

I don't really know any advantages of overriding individual models in a module this way besides being able to make the models have additional fields so you don't have to do something like define a UserProfile model to add extra features to User, though.

No comments:

Post a Comment