""" 修复数据库中文件路径的反斜杠问题 将所有 Windows 风格的反斜杠路径转换为正斜杠 """ import os import django # 设置 Django 环境 os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'application.settings') django.setup() from dvadmin.system.models import FileList from crud_book.models import CrudBookModel def fix_file_list_paths(): """修复 FileList 表中的路径""" print("开始修复 FileList 表中的路径...") # 修复 url 字段 files_with_backslash = FileList.objects.filter(url__contains='\\') count = 0 for file_obj in files_with_backslash: old_url = str(file_obj.url) new_url = old_url.replace('\\', '/') file_obj.url = new_url file_obj.save(update_fields=['url']) count += 1 print(f" 修复: {old_url} -> {new_url}") print(f"FileList.url: 共修复 {count} 条记录") # 修复 file_url 字段 files_with_backslash = FileList.objects.filter(file_url__contains='\\') count = 0 for file_obj in files_with_backslash: old_url = file_obj.file_url new_url = old_url.replace('\\', '/') file_obj.file_url = new_url file_obj.save(update_fields=['file_url']) count += 1 print(f" 修复: {old_url} -> {new_url}") print(f"FileList.file_url: 共修复 {count} 条记录") def fix_book_paths(): """修复图书表中的路径""" print("\n开始修复图书表中的路径...") # 修复 image 字段 books_with_backslash = CrudBookModel.objects.filter(image__contains='\\') count = 0 for book in books_with_backslash: old_path = book.image new_path = old_path.replace('\\', '/') book.image = new_path book.save(update_fields=['image']) count += 1 print(f" 修复封面: {book.title} - {old_path} -> {new_path}") print(f"CrudBookModel.image: 共修复 {count} 条记录") # 修复 file 字段 books_with_backslash = CrudBookModel.objects.filter(file__contains='\\') count = 0 for book in books_with_backslash: old_path = book.file new_path = old_path.replace('\\', '/') book.file = new_path book.save(update_fields=['file']) count += 1 print(f" 修复文件: {book.title} - {old_path} -> {new_path}") print(f"CrudBookModel.file: 共修复 {count} 条记录") if __name__ == '__main__': print("=" * 60) print("开始修复文件路径中的反斜杠问题") print("=" * 60) try: fix_file_list_paths() fix_book_paths() print("\n" + "=" * 60) print("✅ 所有路径修复完成!") print("=" * 60) except Exception as e: print(f"\n❌ 修复过程中出现错误: {e}") import traceback traceback.print_exc()