How to Organize Your Models

Posted by Chris Bartos on July 11, 2017

How many models do you have in your file? If your app has 1 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 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 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:


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

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

Then, in your 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 file, give this little trick a try!

Similar Posts

What 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:

  1. Start writing tests
  2. Increase the size / complexity of the Polls application.
  3. Learn how to code in Django by reading the Django source code.
  4. Finding code snippets to use in your website by reading the code of other websites.
  5. Using Javascript in a web app.
  6. Deploying on Heroku and AWS.
We won't send you spam. Unsubscribe at any time. Powered by ConvertKit

Get some value from this post? Please like and share this post because more people also deserve some value. :-)