skip to Main Content

I am trying to create a custom command on Django, which will use the sqlsequencereset command for a list of app labels inside a loop, the idea is to run this command to generate and run the sequence setval query for each table of the app.

My implementation:

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

I read inside the Django Documentation that raw queries inside cursor.execute do not support transactions, so i customized the SQL string to not include BEGIN and COMMIT keywords, but it still throws the following syntax error:

 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;

2

Answers


  1. Chosen as BEST ANSWER

    So apparently the styling of the output text was colored, which led to the cursor not being able to process it inside the query console, I was able to get it working by using the no_color argument with the sqlsequencereset command:

        for app_label in app_labels:
            output = call_command("sqlsequencereset", app_label, no_color=True, database='default')
            with connection.cursor() as cursor:
                cursor.execute(output)
    

  2. The call_command(…) function [Django-doc] does not return what the command prints. The command just prints to the stdout.

    You can catch the output by storing the stdout in a StringIO we can catch the result, and thus use that in the query:

    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())
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search