How to reset the sequence for IDs on PostgreSQL tables

北慕城南 提交于 2019-11-27 19:49:19
Dmitry Shevchenko

Run sqlsequencereset and it'll print all the reset commands you need.

As suggested by "Dmitry Shevchenko" you can run sqlsequencereset to solve your problem.

or

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.

Here's a short snippet to reset all sequences in Django 1.9+ (based on http://djangosnippets.org/snippets/2774/) and compatible with Python 3:

import os
from io import StringIO

os.environ['DJANGO_COLORS'] = 'nocolor'

from django.core.management import call_command
from django.apps import apps
from django.db import connection

commands = StringIO()
cursor = connection.cursor()

for app in apps.get_app_configs():
    label = app.label
    call_command('sqlsequencereset', label, stdout=commands)

cursor.execute(commands.getvalue())

PostgreSQL Command: ALTER SEQUENCE app_model_id_seq RESTART WITH 1

select setval('django_comments_id_seq', 12345);

This snippet Run sqlsequencereset on all apps reset all IDs of all Empty Models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!