Andrew Wilkinson

Random Ramblings on Programming

Placing Django Models In Separate Files

with 5 comments

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!


Written by Andrew Wilkinson

January 20, 2009 at 1:20 pm

Posted in web development

Tagged with

5 Responses

Subscribe to comments with RSS.

  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


    June 18, 2009 at 5:28 am

  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.

    Andrew Wilkinson

    June 18, 2009 at 12:24 pm

  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).


    March 4, 2010 at 9:42 pm

  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?


    May 20, 2011 at 12:12 pm

    • 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.


      Andrew Wilkinson

      May 20, 2011 at 1:34 pm

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

%d bloggers like this: