Multiple Files for Django Models

One of the first things I noticed when I started with Django was that models and views were single files. Now I’ve read various opinions on how things should be handled (multiple modules vs. multiple files) but I’m of the opinion that clarity is always better. So even if you have a single model, I’d rather have the file be named something descriptive rather than the generic

Breaking things up into multiple files is quite straight-forward – delete, create a models directory, add and create your model classes. Here’s an example:

from blog import Blog
from blogcomment import BlogComment

view raw

hosted with ❤ by GitHub

Note: In order for syncdb to see your models and work correctly, you’ll need to import the models in


from django.db import models
class Blog(models.Model):
title = models.CharField(max_length=255)
slug = models.CharField(max_length=255)
author = models.CharField(max_length=100)
blog = models.TextField()
image = models.CharField(max_length=20)
tags = models.TextField()
created = models.DateTimeField('date created', auto_now_add=True)
updated = models.DateTimeField('last updated', auto_now_add=True, auto_now=True)
def __unicode__(self):
return self.title
class Meta:
app_label = 'app'

view raw

hosted with ❤ by GitHub

Note: The Meta class is necessary for Django to associate the model correctly. Just set it to the name of your application. Otherwise syncdb won’t see your models or you’ll get a lovely error like the following when one of your models contains a foreign key:

CommandError: One or more models did not validate:
app.blogcomment: 'blog' has a relation with model <class ''>, which has either not been installed or is abstract.

view raw

hosted with ❤ by GitHub

You can then import your models like this:

# import one model
from app.models import Blog
# import a bunch
from app.models import *

view raw

hosted with ❤ by GitHub

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 )

Connecting to %s