简体   繁体   English

Django第二个DB返回None

[英]Django second DB returns None

To set up the two databases I followed the documentation which includes: 为了建立两个数据库,我遵循了文档,其中包括:

  • Adding the DB information in setting.py DATABASES={} 在setting.py DATABASES = {}中添加数据库信息
  • Created a matching model of the model from another DB 从另一个数据库创建了该模型的匹配模型
  • Run migrate (Which created a blank table for the model in second DB) 运行迁移(在第二个数据库中为模型创建了一个空白表)

    from client_portal.models import client_names 从client_portal.models导入client_names

      def try_names(request): cn = client_portal.objects.using('second_db').filter(client_id='170155').last() 

    print(cn.last_name) 打印(cn.last_name)

cn is None. cn为None。 It shouldn't because the data exists in the second DB. 这不应该是因为数据存在于第二个数据库中。 My assumption is it's querying the data from the default db because I missed a step. 我的假设是它从默认数据库中查询数据,因为我错过了一步。

Do I need to 'install' a router even if I will use using() exclusively? 即使仅使用using(),我是否也需要“安装”路由器? If so, where do I save the file? 如果是这样,我应该在哪里保存文件?

DATABASE_ROUTERS = ['path.to.AuthRouter', 'path.to.PrimaryReplicaRouter']

That example was from the documentation. 该示例来自文档。 Where does Django expect the router file? Django在哪里期望路由器文件?

Thank you for help. 谢谢你的帮助。

As it turns out, migrate names the tables as [app]_[model_name] and thus with different app names on different projects, I was initially accessing the table migrate --database=created. 事实证明,迁移表的名称为[app] _ [model_name],因此在不同项目上使用不同的应用程序名称,我最初访问的是表迁移--database = created。

To access the table on another server, match the table names on both database servers by using in models.py: 要访问另一台服务器上的表,请通过使用models.py来匹配两台数据库服务器上的表名:

class Meta:
    app_label = [app1_this]
    db_table = [app_another]_[model_name]

If someone else has a better solution, please let me know. 如果其他人有更好的解决方案,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM