File tree Expand file tree Collapse file tree 1 file changed +20
-15
lines changed
apps/knowledge/migrations Expand file tree Collapse file tree 1 file changed +20
-15
lines changed Original file line number Diff line number Diff line change 11# Generated by Django 5.2.4 on 2025-08-11 09:45
22
3- from django .db import migrations , models
3+ from django .db import migrations , models , connection
4+
45
5- from django .db .models import Q
66
77
88def add_allow_download_to_existing_documents (apps , schema_editor ):
9- Document = apps .get_model ('knowledge' , 'Document' )
10-
11- # 为所有现有的Document记录添加allow_download=True
12- documents = Document .objects .filter (
13- Q (meta__isnull = True ) |
14- ~ Q (meta__has_key = 'allow_download' )
15- )
16-
17- for doc in documents :
18- if doc .meta is None :
19- doc .meta = {}
20- doc .meta ['allow_download' ] = True
21- doc .save (update_fields = ['meta' ])
9+
10+ # 使用原生SQL进行批量更新,避免加载大量对象到内存
11+ with connection .cursor () as cursor :
12+ # 为meta为null的记录设置初始值
13+ cursor .execute ("""
14+ UPDATE document
15+ SET meta = '{"allow_download": true}'::jsonb
16+ WHERE meta IS NULL
17+ """ )
18+
19+ # 为meta不包含allow_download键的记录添加该字段
20+ cursor .execute ("""
21+ UPDATE document
22+ SET meta = meta || '{"allow_download": true}'::jsonb
23+ WHERE meta IS NOT NULL
24+ AND NOT (meta ? 'allow_download')
25+ """ )
26+
2227
2328class Migration (migrations .Migration ):
2429
You can’t perform that action at this time.
0 commit comments