SillaAMP_V2/B_main/manual_populate.py

170 lines
5.6 KiB
Python
Raw Permalink Normal View History

#!/usr/bin/env python
"""
수동으로 Person 데이터를 초기화하고 peopleinfo.py의 데이터로 채우는 스크립트
사용법:
python manage.py shell
exec(open('B_main/manual_populate.py').read())
"""
import os
import sys
import django
from datetime import datetime
# Django 설정
import sys
import os
# 프로젝트 루트 경로를 Python 경로에 추가
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_root)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'A_core.settings')
django.setup()
from django.contrib.auth.models import User
from B_main.models import Person
from B_main.peopleinfo import PEOPLE
def clear_existing_persons():
"""superuser를 제외한 모든 Person을 삭제"""
print("기존 Person 데이터 정리 중...")
# superuser들 찾기
superusers = User.objects.filter(is_superuser=True)
if superusers.exists():
print(f"Superuser 발견: {superusers.count()}")
# 모든 superuser의 Person들을 보존
preserved_persons = []
for superuser in superusers:
person = Person.objects.filter(user=superuser).first()
if person:
preserved_persons.append(person)
print(f"보존할 Person: {person.이름} (ID: {superuser.id}, 이메일: {superuser.email})")
else:
print(f"Superuser {superuser.username} (ID: {superuser.id}, 이메일: {superuser.email}) - Person 없음")
# 모든 Person 삭제 (superuser들 제외)
deleted_count = Person.objects.exclude(user__in=superusers).delete()[0]
print(f"삭제된 Person 수: {deleted_count}")
# 보존된 Person 중 첫 번째를 반환 (또는 None)
return preserved_persons[0] if preserved_persons else None
else:
print("Superuser를 찾을 수 없습니다.")
# 모든 Person 삭제
deleted_count = Person.objects.all().delete()[0]
print(f"삭제된 Person 수: {deleted_count}")
return None
def parse_birth_date(birth_str):
"""생년월일 문자열을 Date 객체로 변환"""
if not birth_str or birth_str == '':
return None
try:
# "1960.03.27" 형식을 파싱
if '.' in birth_str:
return datetime.strptime(birth_str, '%Y.%m.%d').date()
# "1962" 형식도 처리
elif len(birth_str) == 4:
return datetime.strptime(f"{birth_str}.01.01", '%Y.%m.%d').date()
else:
return None
except ValueError:
print(f"생년월일 파싱 오류: {birth_str}")
return None
def create_persons_from_peopleinfo():
"""peopleinfo.py의 데이터로 Person 객체 생성"""
print("peopleinfo.py 데이터로 Person 생성 중...")
created_count = 0
error_count = 0
for person_data in PEOPLE:
try:
# 기본 필드들
name = person_data.get('이름', '')
affiliation = person_data.get('소속', '')
birth_date = parse_birth_date(person_data.get('생년월일', ''))
position = person_data.get('직책', '')
phone = person_data.get('연락처', '')
address = person_data.get('주소', '')
# 사진 경로에서 'media/' 접두사 제거
photo = person_data.get('사진', 'profile_photos/default_user.png')
if photo.startswith('media/'):
photo = photo[6:] # 'media/' 제거
title = person_data.get('TITLE', '')
sequence = person_data.get('SEQUENCE', None)
# SEQUENCE를 정수로 변환
if sequence and sequence != '':
try:
sequence = int(sequence)
except ValueError:
sequence = None
else:
sequence = None
# 이미 존재하는지 확인
existing_person = Person.objects.filter(이름=name, 연락처=phone).first()
if existing_person:
print(f"이미 존재하는 Person: {name} ({phone})")
continue
# 새 Person 생성
person = Person.objects.create(
이름=name,
소속=affiliation,
생년월일=birth_date,
직책=position,
연락처=phone,
주소=address,
사진=photo,
TITLE=title,
SEQUENCE=sequence
)
created_count += 1
print(f"생성됨: {name} ({phone})")
except Exception as e:
error_count += 1
print(f"오류 발생 ({name}): {str(e)}")
continue
print(f"\n생성 완료: {created_count}")
print(f"오류 발생: {error_count}")
return created_count
def main():
"""메인 실행 함수"""
print("=" * 50)
print("Person 데이터 초기화 및 재생성")
print("=" * 50)
# 1. 기존 데이터 정리
preserved_person = clear_existing_persons()
# 2. peopleinfo.py 데이터로 새로 생성
created_count = create_persons_from_peopleinfo()
# 3. 결과 요약
total_persons = Person.objects.count()
print("\n" + "=" * 50)
print("작업 완료!")
print(f"총 Person 수: {total_persons}")
if preserved_person:
print(f"보존된 Person: {preserved_person.이름} (Superuser)")
print("=" * 50)
if __name__ == "__main__":
# 직접 실행
main()