Django 如何解决 apps aren't loaded yet 错误?

Django how to solve apps aren't loaded yet error?

我正在为我的 Django 项目使用 apscheduler。我试图每 10 秒列出所有用户。 但是当我尝试时出现错误:

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

scheduler.py

from apscheduler.schedulers.background import BackgroundScheduler
from accounts.models import UserProfile

sched = BackgroundScheduler()
def period():
    users = UserProfile.objects.all()
    print(users)
def start():
    sched.add_job(period, 'interval', seconds=10)
    sched.start()

apps.py

from django.apps import AppConfig
from dashboard.scheduler import start

class DashboardConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'dashboard'
    def ready(self):
        start()

accounts/models.py

from django.contrib.auth.models import AbstractUser
from django.db import models


class UserProfile(AbstractUser):
    username = models.CharField(max_length=500, unique=True)
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    password = models.CharField(max_length=250)
    email = models.EmailField(max_length=254)
    isUserActive = models.BooleanField(default=False)

    def __str__(self):
        return self.username

例如,当我这样做时:

def period():
    print("okey!")

正在运行。但是当我尝试获取模型对象时,它会出错。我该如何解决?

回溯

Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "C:\Users\edeni\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner
    self.run()
  File "C:\Users\edeni\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\edeni\Desktop\project\myvenv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\edeni\Desktop\project\myvenv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run
    autoreload.raise_last_exception()
  File "C:\Users\edeni\Desktop\project\myvenv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception
    raise _exception[1]
  File "C:\Users\edeni\Desktop\project\myvenv\lib\site-packages\django\core\management\__init__.py", line 375, in execute
    autoreload.check_errors(django.setup)()
  File "C:\Users\edeni\Desktop\project\myvenv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\edeni\Desktop\project\myvenv\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\edeni\Desktop\project\myvenv\lib\site-packages\django\apps\registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
  File "C:\Users\edeni\Desktop\project\myvenv\lib\site-packages\django\apps\config.py", line 124, in create
    mod = import_module(mod_path)
  File "C:\Users\edeni\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 850, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "C:\Users\edeni\Desktop\project\dashboard\apps.py", line 2, in <module>
    from dashboard.scheduler import start
  File "C:\Users\edeni\Desktop\project\dashboard\scheduler.py", line 2, in <module>
    from accounts.models import UserProfile
  File "C:\Users\edeni\Desktop\project\accounts\models.py", line 1, in <module>
    from django.contrib.auth.models import AbstractUser
  File "C:\Users\edeni\Desktop\project\myvenv\lib\site-packages\django\contrib\auth\models.py", line 3, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "C:\Users\edeni\Desktop\project\myvenv\lib\site-packages\django\contrib\auth\base_user.py", line 48, in <module>
    class AbstractBaseUser(models.Model):
  File "C:\Users\edeni\Desktop\project\myvenv\lib\site-packages\django\db\models\base.py", line 108, in __new__
    app_config = apps.get_containing_app_config(module)
  File "C:\Users\edeni\Desktop\project\myvenv\lib\site-packages\django\apps\registry.py", line 253, in get_containing_app_config
    self.check_apps_ready()
  File "C:\Users\edeni\Desktop\project\myvenv\lib\site-packages\django\apps\registry.py", line 136, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

仅在 ready 函数中导入调度程序模块,否则您将导入序列化程序,因此在 之前 这些模型已加载:

from django.apps import AppConfig
# no import of the sechduler

class DashboardConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'dashboard'
    
    def ready(self):
        # import the scheduler in the ready function
        from dashboard.scheduler import <strong>start</strong>
        start()