0

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

假设我要运行查询:

set names utf8mb4;

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

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

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

4

1 回答 1

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;")

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


注意,如果您只有一个数据库连接,即,default您可以使用:

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

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

DATABASES = {
    'default': {
        ...
        'OPTIONS': {
            "init_command": "set names utf8mb4;"
        }
    }
}
于 2016-12-17T04:11:24.447 回答