Placing Django Models In Separate Files

Chris Petrilli has made a very useful post on placing Django models into separate files.

The first thing I do when starting a Django project is to delete the standard file and replace it with a directory. It won’t take you long before you’ve written enough views that a single file becomes huge. The same is true of If you have ten or more models then the file can quickly become a thousand line behemoth. I’d tried to split the file into a directory before, but it never worked, and the error messages were never helpful.

The solution is simple, you add a Meta class to your model with an app_label parameter.

from django.db import models

class Test(models.Model):
    class Meta:
        app_label = 'myapp'

So, thanks Chris!


Author: Andrew Wilkinson

I'm a computer programmer and team leader working at the UK grocer and tech company, Ocado Technology. I mostly write multithreaded real time systems in Java, but in the past I've worked with C#, C++ and Python.

5 thoughts on “Placing Django Models In Separate Files”

  1. What’s wrong with creating various files in the directory you have? You don’t have to put everything into the or or names the file which holds the view…


    Models import from the relevant model file…

    from apps.hello.hi_models import HelloMessage
    from apps.hello.bye_models import ByeMessage

  2. I think that’s a good solution for small websites, but if you’ve got a largeish website with a number of models and views there’s something to be said for keeping your source files separated. I like to keep my source files tidy, and I think mixing views and models is just going to lead to some confusion.

  3. A note in case someone is searching for it.

    If you’re seeding your app with initial sql data (by specifying sql/.sql) , you’ll need to move the sql dir to be under the new models dir (models/sql/.sql).

  4. Thanks for this post. I spent hours trying to figure out how to do this. But in addition to this I had to import these models in the ‘’ placed in the models directory. I don’t if this is due to some recent change in Django. Any comments?

    1. Hi Vimukthi,

      You’re right, you will need to import them in Django does a ‘from models import *’ to find all the models in app, if you don’ import them it won’t find them.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s