RuntimeError: Model doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS 运行时错误:模型没有声明一个明确的 app_label,并且不在 INSTALLED_APPS 中的一个应用程序中。
RuntimeError: Model doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS 运行时错误:模型没有声明一个明确的 app_label,并且不在 INSTALLED_APPS 中的一个应用程序中。
我正在使用Django编写一个应用程序,尝试进行一些单元测试,但似乎找不到测试失败的原因。以下是测试页面的代码:
import re from django.test import TestCase from django.urls import reverse from . import models class BasicTests(TestCase): def test_firstname(self): print('test11') acc = models.Accounts() acc.first_name = 'Moran' self.assertTrue(len(acc.id) <= 9, '检查名字长度小于50个字符') self.assertFalse(len(acc.id) > 50, '检查名字长度小于50个字符')
我得到的错误是:
RuntimeError: Model class DoggieSitter.accounts.models.Accounts没有声明显式的app_label,并且不在INSTALLED_APPS中的应用程序中
这是我的已安装应用程序列表:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts' ]
当在运行测试时遇到(RuntimeError: Model doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS)错误时,可以尝试以下解决方法。
原因:
该错误通常是由于相对导入引起的。当在测试文件(tests.py)中使用相对导入语句from .models import ModelName
时,可能会导致这个问题。这是因为相对导入可能无法正确找到模型的位置,从而导致模型没有明确的app_label。
解决方法:
1. 显式导入模型:将相对导入语句更改为显式导入语句,例如:from DoggieSitter.accounts import models
。这样可以确保模型被正确导入,并解决错误。
2. 使用绝对导入:如果项目结构较复杂,并且无法使用显式导入语句解决问题,可以尝试使用绝对导入。根据项目结构,使用绝对导入语句from apps.recipes.models import Recipe
来导入模型。这样可以确保模型被正确导入,并解决错误。
3. 使用django.apps模块:另一种更明确的解决方法是使用django.apps模块中的get_model函数。通过以下代码导入模型:
from django.apps import apps Recipe = apps.get_model(app_label='recipes', model_name='Recipe')
这种方法可以确保模型被正确导入,并解决错误。
当出现(RuntimeError: Model doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS)错误时,可以通过显式导入模型、使用绝对导入或使用django.apps模块中的get_model函数来解决问题。这些方法可以确保模型被正确导入,从而解决错误。