import csv from pathlib import Path from uuid import UUID from django.core.management.base import BaseCommand, CommandError from address.models import AddressObject class Command(BaseCommand): help = "Импорт адресных объектов из UTF-8 CSV" def add_arguments(self, parser): parser.add_argument("file", type=Path) parser.add_argument("--batch-size", type=int, default=2000) def handle(self, *args, **options): path = options["file"] required = {"fias_id", "name", "level", "region_code"} if not path.is_file(): raise CommandError(f"Файл не найден: {path}") with path.open(encoding="utf-8-sig", newline="") as source: reader = csv.DictReader(source) missing = required - set(reader.fieldnames or ()) if missing: raise CommandError(f"Нет обязательных колонок: {', '.join(sorted(missing))}") rows = list(reader) existing = { str(item.fias_id): item for item in AddressObject.objects.filter(fias_id__in=[row["fias_id"] for row in rows]) } objects = [] for row in rows: fias_id = UUID(row["fias_id"]) item = existing.get(str(fias_id), AddressObject(fias_id=fias_id)) item.object_id = int(row["object_id"]) if row.get("object_id") else None item.name = row["name"].strip() item.type_name = row.get("type_name", "").strip() item.level = int(row["level"]) item.region_code = row["region_code"].strip().zfill(2) item.postal_code = row.get("postal_code", "").strip() item.is_active = row.get("is_active", "true").lower() in {"1", "true", "yes"} objects.append(item) AddressObject.objects.bulk_create( objects, batch_size=options["batch_size"], update_conflicts=True, unique_fields=("fias_id",), update_fields=( "object_id", "name", "type_name", "level", "region_code", "postal_code", "is_active", ), ) parent_links = { row["fias_id"]: row.get("parent_fias_id", "").strip() for row in rows if row.get("parent_fias_id", "").strip() } if parent_links: imported = { str(item.fias_id): item for item in AddressObject.objects.filter( fias_id__in=set(parent_links) | set(parent_links.values()) ) } children = [] for child_fias_id, parent_fias_id in parent_links.items(): child = imported.get(child_fias_id) parent = imported.get(parent_fias_id) if child and parent: child.parent = parent children.append(child) AddressObject.objects.bulk_update( children, ("parent",), batch_size=options["batch_size"] ) self.stdout.write(self.style.SUCCESS(f"Импортировано: {len(objects)}"))