How to reset the sequence for IDs on PostgreSQL tables

后端 未结 9 937
北荒
北荒 2020-12-05 02:37

I recently imported a lot of data from an old database into a new Postgresql database as the basis for models in a new Django site.

I used the IDs from the old datab

9条回答
  •  隐瞒了意图╮
    2020-12-05 03:31

    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())
    

提交回复
热议问题