48 lines
2.0 KiB
Python
48 lines
2.0 KiB
Python
# management/commands/clear_database.py
|
|
from django.core.management.base import BaseCommand
|
|
from django.db import connection
|
|
from users.models import Employee
|
|
from equipment.models import Computer, Monitor, Peripheral
|
|
|
|
|
|
class Command(BaseCommand):
|
|
help = "Clear all data from equipment and users tables"
|
|
|
|
def add_arguments(self, parser):
|
|
parser.add_argument(
|
|
"--force",
|
|
action="store_true",
|
|
help="Skip confirmation prompt",
|
|
)
|
|
|
|
def handle(self, *args, **options):
|
|
if not options.get("force"):
|
|
confirm = input(
|
|
"This will DELETE ALL data from Employee, Computer, Monitor, and Peripheral tables. Are you sure? (y/n): "
|
|
)
|
|
if confirm.lower() != "y":
|
|
self.stdout.write("Operation cancelled.")
|
|
return
|
|
|
|
# Option A: Using Django's delete() - slower but triggers signals
|
|
Employee.objects.all().delete()
|
|
Computer.objects.all().delete()
|
|
Monitor.objects.all().delete()
|
|
Peripheral.objects.all().delete()
|
|
|
|
# Option B: Using raw SQL TRUNCATE - faster, resets sequences
|
|
with connection.cursor() as cursor:
|
|
# Truncate in correct order to respect foreign key constraints
|
|
cursor.execute("TRUNCATE TABLE equipment_peripheral CASCADE;")
|
|
cursor.execute("TRUNCATE TABLE equipment_monitor CASCADE;")
|
|
cursor.execute("TRUNCATE TABLE equipment_computer CASCADE;")
|
|
cursor.execute("TRUNCATE TABLE users_employee CASCADE;")
|
|
|
|
# Reset auto-increment sequences (if using serial/identity columns)
|
|
cursor.execute("ALTER SEQUENCE users_employee_id_seq RESTART WITH 1;")
|
|
cursor.execute("ALTER SEQUENCE equipment_computer_id_seq RESTART WITH 1;")
|
|
cursor.execute("ALTER SEQUENCE equipment_monitor_id_seq RESTART WITH 1;")
|
|
cursor.execute("ALTER SEQUENCE equipment_peripheral_id_seq RESTART WITH 1;")
|
|
|
|
self.stdout.write(self.style.SUCCESS("Database cleared successfully!"))
|