How to reset the sequence for IDs on PostgreSQL tables

后端 未结 9 939
北荒
北荒 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:20

    based on @Paolo Melchiorre I created a custom management command, which populates all the models from chosen apps.

    from django.core.management.base import BaseCommand
    from django.apps import apps
    from django.core.management.color import no_style
    from django.db import connection
    
    class Command(BaseCommand):
        def handle(self, *args, **kwargs):
            self.stdout.write('Reset AutoFields ...')
            APPS = ['app1', 'app2']
    
            APPS = [apps.get_app_config(app) for app in APPS]
            models = []
            for app in APPS:
                models.extend(list(app.get_models()))
    
            sequence_sql = connection.ops.sequence_reset_sql(no_style(), models)
            with connection.cursor() as cursor:
                for sql in sequence_sql:
                    self.stdout.write(sql)
                    cursor.execute(sql)
            self.stdout.write(self.style.SUCCESS('Reset AutoField complete.'))
    

    tested using python 3.7 and django 2.2.

提交回复
热议问题