Fixing your models subdirectory

For those of you who keep your models in a subdirectory, you may have noticed that you can't properly load fixtures. This is because Django checks for the location of your models file to determine your app directory. To fix this, move your models directory to something like modeldir and create a models.py which imports the models from inside.

Before:

myapp
|__ views.py
|__ __init__.py
|__ models/
|____ __init__.py
|____ mymodel1.py
|____ mymodel2.py

After:

myapp
|__ views.py
|__ __init__.py
|__ modeldir/
|____ __init__.py
|____ mymodel1.py
|____ mymodel2.py
|__ models.py

Where the contents of models.py is:

from myapp.modeldir.mymodel1 import *
from myapp.modeldir.mymodel2 import *

Some folks say that if you have too much code for a single models file, you need to split it into an entirely different application. I think they have a point, but for my particular use case, it just happened that we have one model with a bunch of business rules attached which makes for difficult to scroll code.

UPDATE: A few people asked why not just put the imports into the _init_.py? That was my original approach, which led to the issues. For fixture loading, django attempts to import models, which returns myapp/models/_init_.py. It then gets the directory of this module, myapp/models/ and attempts to find a fixtures directory below that, or myapp/models/fixtures. To circumvent this, you have to make a models.py file which imports from the other directory.

© 2012 - 2023 · Home — Theme Simpleness