from django.contrib.contenttypes.models import ContentType from django.core.management.base import BaseCommand from django.db import connection, ProgrammingError, InternalError from lms.settings import apps class Command(BaseCommand): help = 'Set seq by last id in table.' def handle(self, **_): with connection.cursor() as cursor: for i in ContentType.objects.all(): if i.app_label in apps and not i.model_class().objects.count() == 0: model_name = "%s_%s" % (i.app_label, i.model) cursor.execute('BEGIN') cursor.execute('LOCK TABLE %s IN EXCLUSIVE MODE' % model_name) cursor.execute( """SELECT setval('%s_id_seq', COALESCE( (SELECT MAX(id)+1 FROM %s), 1) ,false )""" % (model_name, model_name) ) cursor.execute('COMMIT')