66 @date:2025/6/10 15:10
77 @desc:
88"""
9- import uuid_utils .compat as uuid
109from functools import reduce
1110from typing import Dict
1211
12+ import uuid_utils .compat as uuid
1313from django .db import transaction
1414from django .db .models import QuerySet
15- from django .db .models .aggregates import Max
15+ from django .db .models .aggregates import Max , Min
1616from django .utils .translation import gettext_lazy as _ , gettext
1717from rest_framework import serializers
1818from rest_framework .utils .formatting import lazy_format
@@ -291,12 +291,10 @@ def post_improve(self, instance: Dict):
291291 problem_paragraph_mappings .append (problem_paragraph_mapping )
292292 chat_record .improve_paragraph_id_list .append (paragraph .id )
293293
294- # 批量保存段落和问题映射
295- max_position = Paragraph .objects .filter (document_id = document_id ).aggregate (
296- max_position = Max ('position' )
297- )['max_position' ]
298- for i , paragraph in enumerate (paragraphs ):
299- paragraph .position = max_position + i + 1
294+ # 处理段落位置
295+ self .prepend_paragraphs (document_id , paragraphs )
296+
297+ # 批量创建新段落和问题映射
300298 Paragraph .objects .bulk_create (paragraphs )
301299 ProblemParagraphMapping .objects .bulk_create (problem_paragraph_mappings )
302300
@@ -308,6 +306,30 @@ def post_improve(self, instance: Dict):
308306
309307 return paragraph_ids , knowledge_id
310308
309+ @staticmethod
310+ def prepend_paragraphs (document_id , paragraphs ):
311+ # 获取所有现有段落
312+ existing_paragraphs = list (Paragraph .objects .filter (
313+ document_id = document_id
314+ ).order_by ('position' ))
315+
316+ # 计算新段落数量
317+ new_count = len (paragraphs )
318+
319+ # 如果已有段落,需要重新调整所有段落的位置
320+ if existing_paragraphs :
321+ # 为现有段落重新分配位置,从新段落数量+1开始
322+ for i , existing_paragraph in enumerate (existing_paragraphs ):
323+ existing_paragraph .position = new_count + i + 1
324+
325+ # 批量更新现有段落位置
326+ if existing_paragraphs :
327+ Paragraph .objects .bulk_update (existing_paragraphs , ['position' ])
328+
329+ # 为新段落分配位置,从1开始
330+ for i , paragraph in enumerate (paragraphs ):
331+ paragraph .position = i + 1
332+
311333
312334class ApplicationChatRecordImproveSerializer (serializers .Serializer ):
313335 chat_id = serializers .UUIDField (required = True , label = _ ("Conversation ID" ))
0 commit comments