在外部 .py 文件中使用 Django 模型

Use django models in an external .py file

我正在尝试制作一个需要访问 Django 应用程序数据库的电报机器人。

我想避免在 views.py 中创建 web 服务来管理内容,因为我不想创建 API 并且只想暂时将内容分开,所以我需要访问到电报机器人中的 django ORM。

我已将模型导入到我的机器人主文件中,但我收到此消息:

File "C:\Python37-32\lib\site-packages\django\apps\registry.py", line 135, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")

django.core.exceptions.AppRegistryNotReady:应用尚未加载。

收到此消息后,我将应用程序添加到设置中,将此行添加到 INSTALLED_APPS 变量:'localadmin.apps.BotConfig' 以及 apps.py 文件中的下一行:

class BotConfig(AppConfig):
    name = 'localadmin.bot'

请记住,有一个名为“bot”的文件夹,其中包含启动 bot 的 main.py 文件。 所以,我认为,一切都井井有条,但是,随着这些变化,我收到了下一条错误消息。

File "C:\Python37-32\lib\site-packages\django\apps\registry.py", line 135, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")

django.core.exceptions.AppRegistryNotReady:应用尚未加载。

所以我想我的问题是我需要使用适当的 django 应用程序来使用模型,但我不能这样做,因为我的应用程序是主要的电报机器人包装器。

我尝试过的另一个选择是将主要包装电报机器人代码放在我的应用程序的 views.py 上,然后,当启动 django 服务器时,在单独的线程上启动电报机器人功能,但是电报信号 returns 一个错误告诉我它只能在主线程上 运行...

所以现在我运行没主意了...

documentation所述

If you’re using components of Django “standalone” – for example, writing a Python script which loads some Django templates and renders them, or uses the ORM to fetch some data – there’s one more step you’ll need in addition to configuring settings.

After you’ve either set DJANGO_SETTINGS_MODULE or called configure(), you’ll need to call django.setup() to load your settings and populate Django’s application registry