代码之家  ›  专栏  ›  技术社区  ›  lofidevops

我可以在没有ORM的情况下从Django查询辅助数据库吗?

  •  1
  • lofidevops  · 技术社区  · 6 年前

    2 回复  |  直到 6 年前
        1
  •  6
  •   Mikhail Burshteyn    6 年前

    您有两种选择:


    1. 只需为第二个数据库安装并导入Python驱动程序( MySQLdb 对于MySQL, psycopg2

    2. 完整的:

      • 在数据库中添加第二个数据库 settings.py :

        DATABASES = {
          'default': {
            # your Django db settings here
          },
          'second': {  # any name can be used
            # your second db settings here
          }
        }
        
      • managed = False table_name Meta .
      • ModelInSecondDb.objects.using('second').all()
      • (可选)添加一个数据库路由器类,该类将自动将这些模型的所有查询定向到 second
        2
  •  0
  •   Sanchit    6 年前

    您可以在django设置中定义其他数据库配置,如:

    DATABASES = {
      'default': {},
      'another_db' : {
        ...
      }
    }
    

    在django ORM中,你可以这样做:

    another_db_table.objects.using('another_db').all()
    

    check out django docs here