How to Organize Your Models

How many models do you have in your models.py file? If your app has 1 models.py file that has a ridiculous number of models (10 - 15) it’s time to break them apart.

So, how do you organize your models so they are easy to find, and work with in the future?

“Fat models” are a good thing, because it prevents your views from getting too bloated. Just look at the internals of the Django User models.

Each of those models have various properties and methods just hanging off them. This is good for the developer because you can put all your calculations and business logic in the model inside a method and just call it normally. Easy peasy!

But, what if you have a models.py file that is just WAY TOO BIG. I’m not just talking about the models themselves, I’m talking about the entire FILE.

One way you can do this is by creating a new folder in your app. You should call this folder: models.

Now, add a __init__.py file along with a file for grouping of models. For example, if I’m recreating that Django User Model file, I might do something like this:

1
2
3
4
5
6
7
.
├── __init__.py
├── groups.py
├── managers.py
└── user.py

0 directories, 4 files

Then, inside each, I’d separate each of the models. For example:

user.py

1
2
3
4
5
class User:
    # blah blah blah

class AnonymousUser:
    # blah blah blah

All the # blah should be the code inside each of those models.

Then, in your __init__.py file, I would import each of those models like:

__init__.py

1
from user import User, AnonymousUser

When you do this, you don’t have to change any of your other code. You will STILL be able to access your models as long as the name of you folder is models by importing them by doing:

views.py

1
from .models import User, AnonymousUser

I hope that helps. Next time you have trouble looking for something in your models.py file, give this little trick a try!

comments powered by Disqus