如何检查Django项目中使用的数据库

时间:2015-09-28 04:37:29

标签: python django

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

如何从settings.DATABASES?

检查数据库

假设这个结构:

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

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

2 个答案:

答案 0 :(得分:8)

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

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

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

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

答案 1 :(得分:0)

from django.conf import settings

if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.postgresql_psycopg2':
   # happy coding