HH/apps/organizations/management/commands/export_sections.py
2026-07-19 12:27:55 +03:00

60 lines
1.7 KiB
Python

"""
Management command to export sections (English name, Arabic name, department) to a CSV file.
Usage:
python manage.py export_sections --output-dir ./exports
"""
import csv
import os
from django.core.management.base import BaseCommand
from apps.organizations.models import Section
class Command(BaseCommand):
help = 'Export sections (English name, Arabic name, department) to a CSV file'
def add_arguments(self, parser):
parser.add_argument(
'--output-dir',
type=str,
default='./exports',
help='Directory to export the sections CSV file to',
)
def handle(self, *args, **options):
output_dir = options['output_dir']
os.makedirs(output_dir, exist_ok=True)
filepath = os.path.join(output_dir, 'sections.csv')
qs = (
Section.objects.all()
.select_related('department')
.order_by('department__name_en', 'name_en')
)
seen = set()
rows = []
for section in qs:
dept = section.department
row = (
section.name_en or '',
section.name_ar or '',
dept.name_en if dept else '',
dept.name_ar if dept else '',
)
if row in seen:
continue
seen.add(row)
rows.append(row)
with open(filepath, 'w', newline='', encoding='utf-8-sig') as f:
writer = csv.writer(f)
writer.writerow(['Name (EN)', 'Name (AR)', 'Department (EN)', 'Department (AR)'])
writer.writerows(rows)
self.stdout.write(self.style.SUCCESS(
f'Exported {len(rows)} unique sections to {filepath}'
))