diff --git a/apps/knowledge/migrations/0002_alter_file_source_type.py b/apps/knowledge/migrations/0002_alter_file_source_type.py index 89c6a60fa..c1696ab50 100644 --- a/apps/knowledge/migrations/0002_alter_file_source_type.py +++ b/apps/knowledge/migrations/0002_alter_file_source_type.py @@ -1,24 +1,29 @@ # Generated by Django 5.2.4 on 2025-08-11 09:45 -from django.db import migrations, models +from django.db import migrations, models, connection + -from django.db.models import Q def add_allow_download_to_existing_documents(apps, schema_editor): - Document = apps.get_model('knowledge', 'Document') - # 为所有现有的Document记录添加allow_download=True - documents = Document.objects.filter( - Q(meta__isnull=True) | - ~Q(meta__has_key='allow_download') - ) + # 使用原生SQL进行批量更新,避免加载大量对象到内存 + with connection.cursor() as cursor: + # 为meta为null的记录设置初始值 + cursor.execute(""" + UPDATE document + SET meta = '{"allow_download": true}'::jsonb + WHERE meta IS NULL + """) + + # 为meta不包含allow_download键的记录添加该字段 + cursor.execute(""" + UPDATE document + SET meta = meta || '{"allow_download": true}'::jsonb + WHERE meta IS NOT NULL + AND NOT (meta ? 'allow_download') + """) - for doc in documents: - if doc.meta is None: - doc.meta = {} - doc.meta['allow_download'] = True - doc.save(update_fields=['meta']) class Migration(migrations.Migration):