问题:如果某些验证检查失败,有没有办法在启动时从DB获取模型并崩溃?
说明:
我有以下模型(简化):
class Configuration(models.Model):
related = models.ForeignKey('other_app.Model')
service_classes = models.CharField(...)
def validate(self):
valid = # checks service_classes against settings.SERVICE_CLASSES - see below
if not self.valid:
raise ValidationException("invalid")
service_classes
包含以逗号分隔的服务类标识符列表,即service_class1,service_class2
。
服务类基本上是这样的:
# module service.py
ServiceClass1(object):
ID = 'service_class1'
ServiceClass2(object):
ID = 'service_class2'
Django设置文件包含为此实例启用的服务类的路径列表:
SERVICE_CLASSES = [
'service.ServiceClass1',
'service.ServiceClass2'
]
但是,由于SERVICE_CLASSES
模型已经创建后可以修改Configuration
,因此它们可能会变得不同步,如果Configuration.service_classes
包含SERVICE_CLASSES
中未找到的类ID,则可能会发生错误{1}}。所以,基本上,我想要做的是在应用程序启动时执行以下代码:
for config in Configuration.models.all():
config.validate() # and let it throw Exception to fail fast
Django docs建议将AppConfig.ready
用于启动初始化代码,但要使用明确的指令以避免以任何方式访问数据库。无论如何我已经尝试了它并且它与OperationalError
崩溃了 - 很可能那个数据库还没有准备好,因为它在syncdb有机会创建数据库之前执行(虽然不确定)。
我已经尝试将它放在models.py中 - 与ValueError: Related model 'other_app.Model' cannot be resolved
崩溃 - 看起来它完全正确,因为在处理models.py
时尚未配置该应用。