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:
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:
Then, inside each, I’d separate each of the models. For example:
# blah should be the code inside each of those models.
Then, in your
__init__.py file, I would import each of those models like:
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:
I hope that helps. Next time you have trouble looking for something in your
models.py file, give this little trick a try!