Django model “doesn't declare an explicit app_label”

后端 未结 28 1956
無奈伤痛
無奈伤痛 2020-11-27 15:38

I\'m at wit\'s end. After a dozen hours of troubleshooting, probably more, I thought I was finally in business, but then I got:

Model class django.contrib.co         


        
28条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 16:08

    I had this error today trying to run Django tests because I was using the shorthand from .models import * syntax in one of my files. The issue was that I had a file structure like so:

        apps/
          myapp/
            models/
              __init__.py
              foo.py
              bar.py
    

    and in models/__init__.py I was importing my models using the shorthand syntax:

        from .foo import *
        from .bar import *
    

    In my application I was importing models like so:

        from myapp.models import Foo, Bar
    

    This caused the Django model doesn't declare an explicit app_label when running ./manage.py test.

    To fix the problem, I had to explicitly import from the full path in models/__init__.py:

        from myapp.models.foo import *
        from myapp.models.bar import *
    

    That took care of the error.

    H/t https://medium.com/@michal.bock/fix-weird-exceptions-when-running-django-tests-f58def71b59a

提交回复
热议问题