【问题标题】:How to check which database is being used in a Django project如何检查 Django 项目中正在使用哪个数据库
【发布时间】:2015-09-28 04:37:28
【问题描述】:

在我的 Django 项目中,如果正在使用 postgresql,我想使用仅在 postgresql 中可用的查询集方法。

如何从 settings.DATABASES 检查数据库?

假设这个结构:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2', # could be: 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'

我的 python 技能太弱,无法遍历字典的结构 =(

【问题讨论】:

    标签: python django


    【解决方案1】:

    要改进 answer posted by Ozgur,在 django shell 中,您需要在调用 print 时加上括号:

    >>> from django.db import connections
    >>> print (connections['default'].vendor)
    'mysql'
    >>> print (connections['reporting'].vendor)
    'postgresql'
    

    【讨论】:

      【解决方案2】:

      这将为您提供在settings.DATABASES 中配置为default 的数据库后端名称:

      >>> from django.db import connection
      >>> print connection.vendor
      'sqlite'
      

      如果您配置了多个数据库:

      >>> from django.db import connections
      >>> print connections['default'].vendor
      'mysql'
      >>> print connections['reporting'].vendor
      'postgresql'
      

      【讨论】:

        【解决方案3】:
        from django.conf import settings
        
        if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.postgresql_psycopg2':
           # happy coding
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-01-05
          • 2013-07-04
          • 2018-08-27
          • 2020-06-20
          • 1970-01-01
          • 2021-12-24
          • 2017-06-19
          • 1970-01-01
          相关资源
          最近更新 更多