建立数据库连接后如何运行SQL查询?

时间:2016-12-16 18:56:01

标签: django django-1.10

我想在网站的生命周期内运行一个命令。我不想多次运行它。

假设我想运行查询:

set names utf8mb4;

然后我会运行类似的东西:

SomeRandomObject.objects.raw('set names utf8mb4;')

我应该把它放在哪里?我运行查询的对象是否重要?有没有更好的对象?

1 个答案:

答案 0 :(得分:1)

我通常从connection对象本身执行此操作。

from django.db import connections
cursor = connections['DATABASE_NAME'].cursor() 
# replace DATABASE_NAME with the name of your
# DATABASE connection, i.e., the appropriate key in the
# settings.DATABASES dictionary
cursor.execute("set names utf8mb4;")

这样您就可以避免使用某些随机模型来运行原始查询。

n.b。如果您只有一个数据库连接,即default,您可以使用:

from django.db import connection
cursor = connection.cursor()
cursor.execute("set names utf8mb4;")

要在启动时运行此功能一次,您可以将以下内容添加到DATABASES

DATABASES = {
    'default': {
        ...
        'OPTIONS': {
            "init_command": "set names utf8mb4;"
        }
    }
}