在Django中间件中导入模型时遭遇App_label相关报错求助
你遇到的这个错误本质上是中间件加载时机早于Django应用初始化完成的时机——Django在启动时会先加载中间件,此时notifications应用的模型还没完成注册,所以直接导入模型或者用错误的AppConfig调用方式都会触发报错。下面给你几个可行的解决方案:
方案1:延迟导入模型到process_request内部
把模型的导入逻辑从模块顶部移到process_request方法内部,这样只有当请求实际进来时才会加载模型,此时所有应用已经完成初始化:
class CheckNotificationMiddleware(object): """ Checks clicked notification to mark it as read """ def process_request(self, request): if request.user.is_authenticated(): # 延迟导入,此时应用已完成初始化 from notifications.models import Notification from django.core.exceptions import ObjectDoesNotExist notification_id = request.GET.get('notification_id') if notification_id: try: notification = Notification.objects.get( pk=notification_id, status=0, recipient=request.user ) notification.status = 1 notification.save() except ObjectDoesNotExist: pass
方案2:正确使用AppConfig获取模型
你之前调用AppConfig.get_model('Notification')的方式有误,需要先获取对应应用的AppConfig实例,再调用get_model方法。推荐用apps.get_model的快捷方式:
from django.apps import apps from django.core.exceptions import ObjectDoesNotExist class CheckNotificationMiddleware(object): """ Checks clicked notification to mark it as read """ def process_request(self, request): if request.user.is_authenticated(): notification_id = request.GET.get('notification_id') if notification_id: # 指定应用标签和模型名获取模型 Notification = apps.get_model('notifications', 'Notification') try: notification = Notification.objects.get( pk=notification_id, status=0, recipient=request.user ) notification.status = 1 notification.save() except ObjectDoesNotExist: pass
也可以显式获取应用的AppConfig实例:
from django.apps import AppConfig from django.core.exceptions import ObjectDoesNotExist class CheckNotificationMiddleware(object): """ Checks clicked notification to mark it as read """ def process_request(self, request): if request.user.is_authenticated(): notification_id = request.GET.get('notification_id') if notification_id: # 先获取notifications应用的配置实例 notifications_app = AppConfig.get_app_config('notifications') Notification = notifications_app.get_model('Notification') try: notification = Notification.objects.get( pk=notification_id, status=0, recipient=request.user ) notification.status = 1 notification.save() except ObjectDoesNotExist: pass
额外检查项
- 确认
notifications应用的models.py中,Notification模型定义正常:如果是自定义应用,无需额外声明app_label(只要应用在INSTALLED_APPS中即可);如果是第三方应用,确保已正确安装(比如通过pip安装的版本适配Django 1.11) - 执行
python manage.py clearcache清除Django缓存,避免旧缓存导致的应用初始化异常
内容的提问来源于stack exchange,提问作者Stephen Nyamweya
相关产品推荐
相关产品推荐

