Django - manage.py sql APPNAME not generating model SQL

前端 未结 2 656
小蘑菇
小蘑菇 2021-01-25 06:13

I have a relatively large flat application that I\'m working on. To maintain separation of concerns, I\'ve split the model and view files into auth_models, d

相关标签:
2条回答
  • 2021-01-25 06:47

    If your auth_models.py contains a model class MyUserModel, you need to put the following in the __init__.py under app/models:

    try:
        from .auth_models import MyUserModel
    except ImportError as e:
        sys.stderr.write("Error: failed to import models module ({})".format(e))
    

    P.S. Another suggestion would be to improve the style you name your files with. Since auth_models.py, dashboard_models.py and taxonomy_models.py are all under app/models you can simply truncate the _models.py ending. I.e. rename your files under /models:

    auth_models.py -> auth.py
    dashboard_models.py -> dashboard.py
    taxonomy_models.py -> taxonomy.py
    

    To import the Model classes as instructed above:

    from .auth import MyUserModel
    
    0 讨论(0)
  • 2021-01-25 06:59

    See this answer.

    Django makes assumptions about your app name from the path in which the models live, so you're forced in this situation to add an app label to every imported model like this:

    class MyModel(Model):
        # Model fields
        class Meta:
            app_label = 'app'
    

    Background:

    As of this writing, Django has the following code to detect an app label for a model:

        if getattr(meta, 'app_label', None) is None:
            # Figure out the app_label by looking one level up.
            # For 'django.contrib.sites.models', this would be 'sites'.
            model_module = sys.modules[new_class.__module__]
            kwargs = {"app_label": model_module.__name__.split('.')[-2]}
    

    From this, we see that it infers the app_label from the modules name, which may exist deep in the app hierarchy.

    0 讨论(0)
提交回复
热议问题