Django's sqlsequencereset command returns the SQL commands needed to reset sequences in the database.
Other similar management commands automatically execute the SQL by default (and only print out the output if you specify the --dry-run option).
From the command line you can execute the returned commands with:
python manage.py sqlsequencereset app1_name app2_name | python manage.py dbshell
But... Is there a way to directly execute the returned code from sqlsequencereset
from inside python?
Manage.py in Django is a command-line utility that works similar to the django-admin command. The difference is that it points towards the project's settings.py file. This manage.py utility provides various commands that you must have while working with Django.
You can execute the SQL query generated by sqlsequencereset
from within python in this way (using the default database):
from django.core.management.color import no_style
from django.db import connection
from myapps.models import MyModel1, MyModel2
sequence_sql = connection.ops.sequence_reset_sql(no_style(), [MyModel1, MyModel2])
with connection.cursor() as cursor:
for sql in sequence_sql:
cursor.execute(sql)
I tested this code with Python3.6, Django 2.0 and PostgreSQL 10.
I'm currently managing this by:
Code:
import io
from django.core.management import call_command
from django.db import connection
app_name = 'my_app'
# Get SQL commands from sqlsequencereset
output = io.StringIO()
call_command('sqlsequencereset', app_name, stdout=output, no_color=True)
sql = output.getvalue()
with connection.cursor() as cursor:
cursor.execute(sql)
output.close()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With