如何使用DjangoAppConfig.ready准备就绪()

2024-04-23 23:18:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我似乎无法让AppConfig下的ready函数正常工作。你知道吗

这是我的密码应用程序.py地址:

from django.apps import AppConfig

from django.contrib.auth.models import User
from django.db.models.signals import post_save, post_delete
from django.db.models import Max, Count
from .models import Player, PlayerStats, TotalLevels

class BloxorsConfig(AppConfig):
    name = 'bloxors'

    def ready(self):
        MaxCurrentLevel = PlayerStats.objects.aggregate(max_levels=Max('level_no'))['max_levels']
        PlayerCount = Player.objects.aggregate(count_players=Count('player_name', distinct=True))['count_players']
        print(MaxCurrentLevel, PlayerCount)

我在文档中读到,ready()每次在manage.py runserver开头都会被调用,但是为什么什么都没有发生呢。理想情况下,我希望它打印两个值MaxCurrentLevel, PlayerCount。你知道吗

有人能指出我做错了什么并帮助解决这个问题吗?你知道吗

一如既往,我非常感谢你的回答!你知道吗


Tags: djangofrompyimportdbmodelscountpost
2条回答

好吧,一开始我有点傻,但我找到了答案,其他任何人都想知道,就在这里!你知道吗

未安装的应用程序: 我已将我的应用程序安装为: 'bloxors'

但显然在文档中(经过大量的挖掘之后),您需要将其指定为:

'bloxors.apps.BloxorsConfig'

给出的理由是,django没有设置默认的AppConfig,这是由用户自己决定的,我不知道,所以给你!你知道吗

看看这个https://docs.djangoproject.com/en/2.2/ref/applications/#django.apps.AppConfig.ready

不能在appconfig中使用模块级导入,而是在ready中使用导入。你知道吗


from django.apps import AppConfig

class BloxorsConfig(AppConfig):
    name = 'bloxors'

    def ready(self):
     # moved impors here
     from django.contrib.auth.models import User
     from django.db.models.signals import post_save, post_delete
     from django.db.models import Max, Count
     from .models import Player, PlayerStats, TotalLevels

        MaxCurrentLevel = PlayerStats.objects.aggregate(max_levels=Max('level_no'))['max_levels']
        PlayerCount = Player.objects.aggregate(count_players=Count('player_name', distinct=True))['count_players']
        print(MaxCurrentLevel, PlayerCount)

相关问题 更多 >