fix commas

This commit is contained in:
pacnpal
2024-11-03 20:21:39 +00:00
parent 1b0fe4588e
commit ed585e6a56
21 changed files with 390 additions and 98 deletions

View File

@@ -0,0 +1,99 @@
# history_tracking/management/commands/initialize_history.py
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.apps import apps
from django.db.models import Model
from simple_history.models import HistoricalRecords
class Command(BaseCommand):
help = "Initialize history records for existing objects with historical records"
def add_arguments(self, parser):
parser.add_argument(
"--model",
type=str,
help="Specify model in format app_name.ModelName (e.g., history_tracking.Park)",
)
parser.add_argument(
"--all",
action="store_true",
help="Initialize history for all models with historical records",
)
parser.add_argument(
"--force",
action="store_true",
help="Create history even if records already exist",
)
def initialize_model(self, model, force=False):
total = model.objects.count()
initialized = 0
model_name = f"{model._meta.app_label}.{model._meta.model_name}"
self.stdout.write(f"Processing {model_name}: Found {total} records")
for obj in model.objects.all():
try:
if force or not obj.history.exists():
obj.history.create(
history_date=timezone.now(),
history_type="+",
history_change_reason="Initial history record",
**{
field.name: getattr(obj, field.name)
for field in obj._meta.fields
if not isinstance(field, HistoricalRecords)
},
)
initialized += 1
self.stdout.write(f"Created history for {model_name} id={obj.pk}")
except Exception as e:
self.stdout.write(
self.style.ERROR(
f"Error creating history for {model_name} id={obj.pk}: {str(e)}"
)
)
return initialized, total
def handle(self, *args, **options):
if not options["model"] and not options["all"]:
self.stdout.write(
self.style.ERROR("Please specify either --model or --all")
)
return
force = options["force"]
total_initialized = 0
total_records = 0
if options["model"]:
try:
app_label, model_name = options["model"].split(".")
model = apps.get_model(app_label, model_name)
if hasattr(model, "history"):
initialized, total = self.initialize_model(model, force)
total_initialized += initialized
total_records += total
else:
self.stdout.write(
self.style.ERROR(
f'Model {options["model"]} does not have historical records'
)
)
except Exception as e:
self.stdout.write(self.style.ERROR(str(e)))
else:
# Process all models with historical records
for model in apps.get_models():
if hasattr(model, "history"):
initialized, total = self.initialize_model(model, force)
total_initialized += initialized
total_records += total
self.stdout.write(
self.style.SUCCESS(
f"Successfully initialized {total_initialized} of {total_records} total records"
)
)