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:
. ├── __init__.py ├── groups.py ├── managers.py └── user.py 0 directories, 4 files
Then, inside each, I’d separate each of the models. For example:
class User: # blah blah blah class AnonymousUser: # blah blah blah
# blah should be the code inside each of those models.
Then, in your
__init__.py file, I would import each of those models like:
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:
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!
Similar PostsWhat do you do when 'makemigrations' is telling you About your Lack of Default Value
How to Implement Many-To-Many Relationship in Django
Test your Queries before they make it into Production using the Django Shell
I have a ChoiceField Callable that Includes a Queryset but it Breaks my Django app
How to filter a DateTimeField by today's date in Django
Help! My Models feel Bloated! Why you should write a custom Manager
What do you do after the Official Django Tutorial?
Here's what you'll learn:
- Start writing tests
- Increase the size / complexity of the Polls application.
- Learn how to code in Django by reading the Django source code.
- Finding code snippets to use in your website by reading the code of other websites.
- Deploying on Heroku and AWS.