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

How do I run SQL queries after a DB connection is established?

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

假设我想 运行 查询:

set names utf8mb4;

然后我会运行像这样:

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

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

我通常在 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;"
        }
    }
}