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!

Want to read more like this? Follow me with your favourite feed reader (e.g. Feedly), or subscribe to my SubStack newsletter.

Comments

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

john

18 Jun 2009

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

18 Jun 2009

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

Ivan

04 Mar 2010

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?

Vimukthi

20 May 2011

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

Andrew Wilkinson

20 May 2011