Model in sub-directory via app_label?

99封情书 提交于 2019-12-18 12:18:23

问题


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?


回答1:


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?




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/2480060/model-in-sub-directory-via-app-label

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!