Code


Version 2 (modified by Malcolm Tredinnick <malcolm@…>, 8 years ago) (diff)

Added a note about app_label being important (it is the secret key to the whole thing)

CookBook - Data Models - Splitting models across multiple files

To split models across multiple files, you can do the following (works at least with revision 2819):

The important thing to notice here is the app_label attribute in the Meta class. If that is omitted, a subsequent manage.py syncdb run will not pick up these models.

apps/polls/models/__init__.py:

from poll import Poll
from choice import Choice

apps/polls/models/poll.py:

from django.db import models

class Poll(models.Model):
    question = models.CharField(maxlength=200)
    pub_date = models.DateTimeField('date published')

    class Meta:
        app_label = 'polls'

apps/polls/models/choice.py:

from django.db import models
from poll import Poll

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(maxlength=200)
    votes = models.IntegerField()

    class Meta:
        app_label = 'polls'

Ok so the example is a bit stupid but it should illustrate the point.