January 29, 2008

Breaking Apart Models in Django

Cover image

Depending on the size of your models.py, you may find it becoming unwieldy, especially if you are on a team with multiple developers are editing the same file, increasing the odds for merge conflicts.

There are two parts to breaking up a large module in Django. The first is a purely Python convention where you break apart the file into multiple files and create a subdirectory for the name of the original module so your models.py file becomes:


Inside your __init__.py you'll want to import from your module1.py and module2.py modules and add those imported objects to __all__:

# __init__.py
from app.models.module1 import MyClass
from app.models.module2 import AnotherClass, function_one
__all__ = ['MyClass', 'AnotherClass', 'function_one']

Now that you have taken care of the Python part of this exercise, you'll need to do a couple tricks to get your models importing properly in the context of your django project.

It involves adding a couple o attributes to the Meta inner class. Thanks to Collin Grady (aka Magus on #django on irc.freenode.net) for pointing these tips out to me:

class MyClass:
    class Meta:
        app_name = 'myappname'
        db_table = 'myappname_myclass'

Now you should have a better code base that causes less contention and makes it faster to locate the models you are looking for.


As has been pointed out to me in the comments as well as one #djano today, I got "Empty" and "Magus" mixed up with their real names. Much apologies for any and all confusion this might have caused.

Update 2

As pointed out in some of the recent comments below, this post was corrupted when I enabled the markdown plugin for wordpress. It is treating all posts I have ever written as markdown which is not right but I have not the energy nor the inclination to go back in time and update all my old posts. That being said, I really love markdown for my posting so I'll keep the plugin activated.