Django:检测数据库后端 [英] Django: Detect database backend

查看:327
本文介绍了Django:检测数据库后端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django中做了一些额外的查询,需要在sqlite和postgres上工作。这些查询的语法在后端之间有所不同,但我没有办法弄清楚是否将查询发送到postgres或sqlite。

I'm doing some "extra" queries in Django that need to work on both sqlite and postgres. The syntax of these queries varies between backend but I have no way of figuring out if I'm sending my queries to either postgres or sqlite.

有办法当前数据库适配器,以便我可以分支我的代码,并发送正确的查询活动数据库服务器?

Is there a way to get the current database adapter so I can branch my code and send the right query for the active database server?

推荐答案

两种方式做,因为@ Ricola3D说有检查 settings.DATABASES ['default'] ['ENGINE'] 的选项:

OK, so there's two ways of doing it, as @Ricola3D said there's the option of checking settings.DATABASES['default']['ENGINE']:

>>> from django.conf import settings
>>> settings.DATABASES['default']['ENGINE']
'django.db.backends.sqlite3' or 'django.db.backends.postgresql_psycopg2'

但是连接上还有一个(未公开的)供应商属性:

But there's also an (undocumented) vendor property on a connection:

>>> from django.db import connection
>>> connection.vendor
'postgresql' or 'sqlite'

我个人更喜欢 connection.vendor ,因为它看起来更漂亮:)

Either way works. I personally prefer connection.vendor as it looks prettier :)

这篇关于Django:检测数据库后端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆