Proposal for splitting out models from a singular file

If you follow the Django tutorial, we have the following basic files:
app/models.py
app/views.py

If you’re familiar with Rails, you have something like
models/model1
models/model2

I was discussing a bit in the #django chat room a few days ago about this, and the argument that was given is that if you’re going to have that large of models, that splitting the application out is a good idea. I agree with this a lot, actually. You can have a different application, that doesn’t actually get mapped to a view. So…you can have something like a blogs application, and a blog_comments application if you so desire. Personally I wouldn’t go this far….

What I feel is better, in the case of the blog application is to have the blog, comments, subject, and so on as individual models. This is what the tutorial already does. The problem I see, though, is that if you put more of your business logic into the model (where it should be, to follow DRY), then these models can get extremely large. There is a way around all this actually.

You can create a models directory, within your application directory, and split out the large model into separate models. The way I refactored the Cab application recently was to do something like:
cab/models/__init__.py – I’ll describe this later
cab/models/Bookmark.py
cab/models/Language.py

In the __init__.py, you need to include each of the separate models, for example:
from Bookmark import Bookmark
from Language import Language

Personally, while it’s annoying to edit the __init__.py file all the time, I find this much cleaner. I feel that perhaps if I have some time I’ll create a function for manage.py so that it can auto-generate this file on demand. That would save a whole lot of work for me.

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay

Comments are closed.