首页 > 解决方案 > 在 django 应用程序中获取所有模型名称时出错

问题描述

我在我的 django 应用程序中使用不同的数据库,而数据库路由时,我试图让所有模型使用

all_models = dict([(name.lower(), cls) for name, cls in app.models.__dict__.items() \
 if isinstance(cls, type)])

在运行迁移时,我收到错误“未定义名称应用程序”。

这是我的 routers.py

from .models import *



  allmodels = dict([(name.lower(), cls) for name, cls in 
  app.models.__dict__.items() \
 if isinstance(cls, type)])

class MyDBRouter(object):

def db_for_read(self, model, **hints):
    """ reading model based on params """
    return getattr(model.params, 'db')

def db_for_write(self, model, **hints):
    """ writing model based on params """
    return getattr(model.params, 'db')

def allow_migrate(self, db, app_label, model_name = None, **hints):
    """ migrate to appropriate database per model """
    model = allmodels.get(model_name)
    return(model.params.db == db)

Settings.py https://pastebin.com/0XdpqxkJ

标签: djangodjango-modelsroutesmulti-database

解决方案


推荐阅读