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 views.py 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 models.py. 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!

Advertisements

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 views.py or models.py or forms.py.

    urls.py names the file which holds the view…

    (‘^hello/$’,’apps.module.hello_view’)
    (‘^goodbye/$’,’apps.module.goodbye_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 ‘__init__.py’ 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 __init__.py. Django does a ‘from models import *’ to find all the models in app, if you don’ import them it won’t find them.

      Andrew

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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