16

In order to place my models in sub-folders I tried to use the app_label Meta field as described here.

My directory structure looks like this:

  • project
    • apps
      • foo
        • models
          • __init__.py
          • bar_model.py

In bar_model.py I define my Model like this:

from django.db import models

class SomeModel(models.Model):

    field = models.TextField()

    class Meta:
        app_label = "foo"

I can successfully import the model like so:

from apps.foo.models.bar_model import SomeModel

However, running:

./manage.py syncdb

does not create the table for the model. In verbose mode I do see, however, that the app "foo" is properly recognized (it's in INSTALLED_APPS in settings.py). Moving the model to models.py under foo does work.

Is there some specific convention not documented with app_label or with the whole mechanism that prevents this model structure from being recognized by syncdb?

kahara
  • 103
  • 1
  • 3
nikola
  • 2,241
  • 4
  • 30
  • 42

3 Answers3

22

See Django ticket #10985: Explain how models can be organised in a directory

It may be that you aren't importing your models into __init__.py?

Community
  • 1
  • 1
Van Gale
  • 43,536
  • 9
  • 71
  • 81
  • 3
    Thanks! Yeah, you'll need to import them into `__init__.py` and give them an `app_label` via the model's `Meta` class. – mustafa.0x Aug 25 '13 at 13:14
  • Important the addition from @mustafa.0x you *must* provide same app_label than the label name you provide as module name or the one you provide in AppConfig registry if not it would return an empty OrderedDict() if you get apps.get_app_config('app_label').models after importing django.apps.apps – danius Jun 10 '15 at 16:31
3

syncdb will not create tables for models not located in <appname>.models, so import it in there, e.g. from apps.foo.models import SomeModel.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • Nope, that doesn't work either, i.e. syncdb doesn't pick up SomeModel. – nikola Mar 19 '10 at 19:58
  • EDIT: I now realize you were pointing in the same direction as Van Gale. I've marked his as the correct answer because it also contains a link to the discussion about proper documentation of app_label. – nikola Mar 19 '10 at 21:43
1

Here is a solution if you have a newer version of Django, supposing you have a subfolder named subfolder :

in apps.py of your folder app:

from django.apps import AppConfig

class MyappConfig(AppConfig):
    name = 'myapp'

    def ready(self):
        from myapp.subfolder import models
David Dahan
  • 10,576
  • 11
  • 64
  • 137