Django:在自定义命令中以编程方式使用 sqlsequencereset

问题描述 投票:0回答:1

我正在尝试在 Django 上创建一个自定义命令,它将使用

sqlsequencereset
命令来获取循环内的应用程序标签列表,其想法是运行此命令来生成并运行每个表的序列
setval
查询应用程序的。

我的实现:

        for app_label in app_labels:
            output = call_command("sqlsequencereset", app_label)
            with connection.cursor() as cursor:
                cursor.execute(output)

我在 Django 文档中读到

cursor.execute
中的原始查询不支持事务,因此我自定义了 SQL 字符串以不包含
BEGIN
COMMIT
关键字,但它仍然抛出以下语法错误:

 File "/home/python/.local/lib/python3.12/site-packages/django/db/backends/utils.py", line 122, in execute
    return super().execute(sql, params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/python/.local/lib/python3.12/site-packages/django/db/backends/utils.py", line 79, in execute
    return self._execute_with_wrappers(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/python/.local/lib/python3.12/site-packages/django/db/backends/utils.py", line 92, in _execute_with_wrappers
    return executor(sql, params, many, context)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/python/.local/lib/python3.12/site-packages/django/db/backends/utils.py", line 100, in _execute
    with self.db.wrap_database_errors:
  File "/home/python/.local/lib/python3.12/site-packages/django/db/utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/python/.local/lib/python3.12/site-packages/django/db/backends/utils.py", line 103, in _execute
    return self.cursor.execute(sql)
           ^^^^^^^^^^^^^^^^^^^^^^^^
django.db.utils.ProgrammingError: syntax error at or near "
LINE 1: BEGIN;
django postgresql command
1个回答
0
投票

call_command(…)
函数[Django-doc]返回命令打印的内容。该命令仅打印到标准输出。

您可以通过将标准输出存储在

StringIO
中来捕获输出,我们可以捕获结果,从而在查询中使用它:

from io import StringIO

output = StringIO()
for app_label in app_labels:
    output = call_command('sqlsequencereset', app_label, stdout=output)
    with connection.cursor() as cursor:
        cursor.execute(output.getvalue())
© www.soinside.com 2019 - 2024. All rights reserved.