You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
246 lines
9.3 KiB
246 lines
9.3 KiB
#!/usr/bin/env python3
|
|
"""
|
|
Script to clear existing hadis data created by seeding scripts.
|
|
This script safely removes all hadis-related data while preserving
|
|
other application data.
|
|
"""
|
|
|
|
import os
|
|
import sys
|
|
import django
|
|
from pathlib import Path
|
|
from django.db import transaction
|
|
|
|
# Setup Django environment
|
|
BASE_DIR = Path(__file__).resolve().parent.parent
|
|
sys.path.append(str(BASE_DIR))
|
|
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
|
|
django.setup()
|
|
|
|
# Import models after Django setup
|
|
from apps.hadis.models import (
|
|
HadisSect, HadisCategory, HadisStatus, HadisTag, Hadis,
|
|
Transmitters, HadisTransmitter, HadisReference, ReferenceImage
|
|
)
|
|
from apps.library.models import Book, Category as LibraryCategory, BookCollection
|
|
|
|
|
|
class HadisDataCleaner:
|
|
"""Class to safely clear hadis data"""
|
|
|
|
def __init__(self):
|
|
pass
|
|
|
|
def show_current_data(self):
|
|
"""Show current data counts"""
|
|
print("=== ТЕКУЩИЕ ДАННЫЕ ===")
|
|
print(f"HadisSect: {HadisSect.objects.count()}")
|
|
print(f"HadisCategory: {HadisCategory.objects.count()}")
|
|
print(f"HadisStatus: {HadisStatus.objects.count()}")
|
|
print(f"HadisTag: {HadisTag.objects.count()}")
|
|
print(f"Hadis: {Hadis.objects.count()}")
|
|
print(f"Transmitters: {Transmitters.objects.count()}")
|
|
print(f"HadisTransmitter: {HadisTransmitter.objects.count()}")
|
|
print(f"HadisReference: {HadisReference.objects.count()}")
|
|
print(f"ReferenceImage: {ReferenceImage.objects.count()}")
|
|
print(f"Books: {Book.objects.count()}")
|
|
print(f"Library Categories: {LibraryCategory.objects.count()}")
|
|
print(f"Book Collections: {BookCollection.objects.count()}")
|
|
|
|
# Show sample data
|
|
print("\n=== ОБРАЗЦЫ ДАННЫХ ===")
|
|
if HadisSect.objects.exists():
|
|
print("HadisSect samples:")
|
|
for sect in HadisSect.objects.all()[:3]:
|
|
print(f" - {sect.title}")
|
|
|
|
if HadisStatus.objects.exists():
|
|
print("HadisStatus samples:")
|
|
for status in HadisStatus.objects.all()[:3]:
|
|
print(f" - {status.title}")
|
|
|
|
if HadisTag.objects.exists():
|
|
print("HadisTag samples:")
|
|
for tag in HadisTag.objects.all()[:5]:
|
|
print(f" - {tag.title}")
|
|
|
|
if Transmitters.objects.exists():
|
|
print("Transmitters samples:")
|
|
for trans in Transmitters.objects.all()[:3]:
|
|
print(f" - {trans.full_name}")
|
|
|
|
if Book.objects.exists():
|
|
print("Books samples:")
|
|
for book in Book.objects.all()[:3]:
|
|
print(f" - {book.title}")
|
|
|
|
@transaction.atomic
|
|
def clear_all_hadis_data(self):
|
|
"""Clear all hadis-related data"""
|
|
print("\n=== ОЧИСТКА ДАННЫХ ХАДИСОВ ===")
|
|
|
|
# Clear in reverse dependency order
|
|
print("Удаление ReferenceImage...")
|
|
count = ReferenceImage.objects.count()
|
|
ReferenceImage.objects.all().delete()
|
|
print(f" Удалено {count} записей ReferenceImage")
|
|
|
|
print("Удаление HadisReference...")
|
|
count = HadisReference.objects.count()
|
|
HadisReference.objects.all().delete()
|
|
print(f" Удалено {count} записей HadisReference")
|
|
|
|
print("Удаление HadisTransmitter...")
|
|
count = HadisTransmitter.objects.count()
|
|
HadisTransmitter.objects.all().delete()
|
|
print(f" Удалено {count} записей HadisTransmitter")
|
|
|
|
print("Удаление Hadis...")
|
|
count = Hadis.objects.count()
|
|
Hadis.objects.all().delete()
|
|
print(f" Удалено {count} записей Hadis")
|
|
|
|
print("Удаление HadisCategory...")
|
|
count = HadisCategory.objects.count()
|
|
HadisCategory.objects.all().delete()
|
|
print(f" Удалено {count} записей HadisCategory")
|
|
|
|
print("Удаление HadisSect...")
|
|
count = HadisSect.objects.count()
|
|
HadisSect.objects.all().delete()
|
|
print(f" Удалено {count} записей HadisSect")
|
|
|
|
print("Удаление HadisStatus...")
|
|
count = HadisStatus.objects.count()
|
|
HadisStatus.objects.all().delete()
|
|
print(f" Удалено {count} записей HadisStatus")
|
|
|
|
print("Удаление HadisTag...")
|
|
count = HadisTag.objects.count()
|
|
HadisTag.objects.all().delete()
|
|
print(f" Удалено {count} записей HadisTag")
|
|
|
|
print("Удаление Transmitters...")
|
|
count = Transmitters.objects.count()
|
|
Transmitters.objects.all().delete()
|
|
print(f" Удалено {count} записей Transmitters")
|
|
|
|
@transaction.atomic
|
|
def clear_library_data(self):
|
|
"""Clear library data that was created by seeding"""
|
|
print("\n=== ОЧИСТКА ДАННЫХ БИБЛИОТЕКИ ===")
|
|
|
|
# Only clear books that seem to be created by seeding script
|
|
# (based on Russian titles or specific patterns)
|
|
russian_book_titles = [
|
|
'Аль-Кафи', 'Сахих аль-Бухари',
|
|
'Ман ля яхдуруху аль-факих', 'Сунан Абу Дауд'
|
|
]
|
|
|
|
books_to_delete = Book.objects.filter(title__in=russian_book_titles)
|
|
count = books_to_delete.count()
|
|
if count > 0:
|
|
books_to_delete.delete()
|
|
print(f" Удалено {count} книг с русскими названиями")
|
|
else:
|
|
print(" Книги с русскими названиями не найдены")
|
|
|
|
# Clear library categories with Russian names
|
|
russian_categories = [
|
|
'Книги хадисов', 'Книги фикха', 'Книги толкования',
|
|
'Книги нравственности', 'Исторические книги'
|
|
]
|
|
|
|
categories_to_delete = LibraryCategory.objects.filter(title__in=russian_categories)
|
|
count = categories_to_delete.count()
|
|
if count > 0:
|
|
categories_to_delete.delete()
|
|
print(f" Удалено {count} категорий библиотеки с русскими названиями")
|
|
else:
|
|
print(" Категории библиотеки с русскими названиями не найдены")
|
|
|
|
# Clear book collections with Russian names
|
|
russian_collections = [
|
|
'Шиитские книги хадисов', 'Суннитские книги хадисов',
|
|
'Сборник книг по фикху'
|
|
]
|
|
|
|
collections_to_delete = BookCollection.objects.filter(title__in=russian_collections)
|
|
count = collections_to_delete.count()
|
|
if count > 0:
|
|
collections_to_delete.delete()
|
|
print(f" Удалено {count} коллекций книг с русскими названиями")
|
|
else:
|
|
print(" Коллекции книг с русскими названиями не найдены")
|
|
|
|
def run_cleanup(self, include_library=True):
|
|
"""Main method to run cleanup"""
|
|
print("=" * 60)
|
|
print("ОЧИСТКА ДАННЫХ ХАДИСОВ")
|
|
print("=" * 60)
|
|
|
|
try:
|
|
# Show current state
|
|
self.show_current_data()
|
|
|
|
# Clear hadis data
|
|
self.clear_all_hadis_data()
|
|
|
|
# Clear library data if requested
|
|
if include_library:
|
|
self.clear_library_data()
|
|
|
|
# Show final state
|
|
print("\n=== ФИНАЛЬНОЕ СОСТОЯНИЕ ===")
|
|
self.show_current_data()
|
|
|
|
print("\n✅ Очистка завершена успешно!")
|
|
|
|
except Exception as e:
|
|
print(f"\n❌ Ошибка при очистке: {e}")
|
|
print("Откат транзакции...")
|
|
raise
|
|
|
|
|
|
def main():
|
|
"""Main function to run the cleanup script"""
|
|
import argparse
|
|
|
|
parser = argparse.ArgumentParser(description='Clear hadis data from database')
|
|
parser.add_argument(
|
|
'--hadis-only',
|
|
action='store_true',
|
|
help='Clear only hadis data, keep library data'
|
|
)
|
|
parser.add_argument(
|
|
'--force',
|
|
action='store_true',
|
|
help='Skip confirmation prompt'
|
|
)
|
|
|
|
args = parser.parse_args()
|
|
|
|
include_library = not args.hadis_only
|
|
|
|
if not args.force:
|
|
print("Это удалит все данные хадисов из базы данных.")
|
|
if include_library:
|
|
print("Также будут удалены связанные данные библиотеки.")
|
|
response = input("Вы уверены? (да/нет): ")
|
|
if response.lower() not in ['да', 'yes', 'y']:
|
|
print("Очистка отменена.")
|
|
return
|
|
|
|
try:
|
|
cleaner = HadisDataCleaner()
|
|
cleaner.run_cleanup(include_library=include_library)
|
|
|
|
except Exception as e:
|
|
print(f"\n❌ Очистка не удалась: {e}")
|
|
import traceback
|
|
traceback.print_exc()
|
|
sys.exit(1)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|