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!

Need help with Django REST Framework? Django REST Framework documentation a little confusing?

Join me for my FREE Django REST Framework email course:

Django REST Framework Email Course

You'll get 1 lesson everyday for 7 days.
You'll learn:

  • Serializers
  • Request Methods
  • Endpoints
  • Basic Authentication
  • JQuery Integration
  • AngularJS Integration
Powered by ConvertKit

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