Splitting your Turbogears SQLObject models

Just a quick note about splitting your model.py file in Turbogears 1.0, when using SQLObject. The Turbogears docs have some notes on this, but there was an extra trick to it in the end.

The model.py file for chrss, was starting to get a bit big, so it seemed like a good time to do this.

First I moved model.py into model/__init__.py. Then I moved all of the model code itself into separate files (three as it happens) and imported them into model/__init__.py as indicated in the Turbogears docs:

from chrss.model.cms import *
from chrss.model.chess import *
from chrss.model.base import *

However that wasn't enough, as the __connection__ module level variable for SQLObject wasn't set and Turbogears couldn't connect to the DB. So I added this to model/__init__.py (before the other imports):

from turbogears.database import PackageHub

hub = PackageHub("chrss")

and then in each file containing models added the following:

from chrss.model import hub
__connection__ = hub

The main trick was to get the import order correct. model/__init__.py must declare the hub variable, before importing the other files, so that they can access it when they are imported. It's a bit of a cyclical dependency, which is maybe not ideal, but it's only used in a limited way.

UPDATE. It turns out that you also need to update the sqlobject.txt file in the .egg-info directory of your project. Otherwise the various tg-admin sql * commands don't work (as it can't find the SQLObject classes). Basically you have to list every sub-package of the newly split model package. e.g. change: