mirror of
https://github.com/cisagov/manage.get.gov.git
synced 2025-08-04 08:52:16 +02:00
updated clean_tables to run in batches of 1000 rows
This commit is contained in:
parent
76d9b8cb8c
commit
a41225be7e
1 changed files with 15 additions and 5 deletions
|
@ -56,14 +56,24 @@ class Command(BaseCommand):
|
|||
self.clean_table(table_name)
|
||||
|
||||
def clean_table(self, table_name):
|
||||
"""Delete all rows in the given table"""
|
||||
"""Delete all rows in the given table.
|
||||
|
||||
Delete in batches to be able to handle large tables"""
|
||||
try:
|
||||
# Get the model class dynamically
|
||||
model = apps.get_model("registrar", table_name)
|
||||
# Use a transaction to ensure database integrity
|
||||
with transaction.atomic():
|
||||
model.objects.all().delete()
|
||||
logger.info(f"Successfully cleaned table {table_name}")
|
||||
BATCH_SIZE = 1000
|
||||
total_deleted = 0
|
||||
while True:
|
||||
pks = list(model.objects.values_list("pk", flat=True)[:BATCH_SIZE])
|
||||
if not pks:
|
||||
break
|
||||
# Use a transaction to ensure database integrity
|
||||
with transaction.atomic():
|
||||
deleted, _ = model.objects.filter(pk__in=pks).delete()
|
||||
total_deleted += deleted
|
||||
logger.debug(f"Deleted {deleted} objects, total deleted: {total_deleted}")
|
||||
logger.info(f"Successfully cleaned table {table_name}, deleted {total_deleted} rows")
|
||||
except LookupError:
|
||||
logger.error(f"Model for table {table_name} not found.")
|
||||
except Exception as e:
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue