From b8ade13b61ba7b7bfd05300192de3038f1f1b7fe Mon Sep 17 00:00:00 2001 From: duxingchen Date: Thu, 13 Aug 2026 09:03:17 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20TaskRecordResponse=E6=94=B9=E7=94=A8fiel?= =?UTF-8?q?d=5Fvalidator=20=E2=80=94=20=E4=B8=8D=E5=86=8D=E6=B1=A1?= =?UTF-8?q?=E6=9F=93ORM=E5=AF=B9=E8=B1=A1=E5=AF=BC=E8=87=B4=E5=9B=BE?= =?UTF-8?q?=E7=89=87=E5=88=97=E8=A1=A8=E5=86=99=E5=9B=9EVARCHAR=E6=8A=A5?= =?UTF-8?q?=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 根因: model_validate直接obj.images=json.loads()把ORM对象的字符串改成列表 SQLAlchemy autoflush时把列表写回VARCHAR列 → DataError 修复: field_validator(mode=before)在序列化层转换, 不修改ORM源对象 --- backend/app/schemas/task.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/backend/app/schemas/task.py b/backend/app/schemas/task.py index d63627a..ea1231b 100644 --- a/backend/app/schemas/task.py +++ b/backend/app/schemas/task.py @@ -3,7 +3,7 @@ from __future__ import annotations import uuid from datetime import datetime from typing import Optional -from pydantic import BaseModel, Field +from pydantic import BaseModel, Field, field_validator # ============================================================ @@ -82,18 +82,19 @@ class TaskRecordResponse(BaseModel): model_config = {"from_attributes": True} + @field_validator("images", mode="before") @classmethod - def model_validate(cls, obj, **kwargs): - """处理 DB 中 images 的 JSON 字符串 → list 反序列化""" + def _parse_images(cls, v): + """处理 DB 中 images 的 JSON 字符串 → list 反序列化(不污染 ORM 对象)""" import json - if hasattr(obj, "images") and isinstance(obj.images, str): + if isinstance(v, str): try: - obj.images = json.loads(obj.images) + return json.loads(v) except (json.JSONDecodeError, TypeError): - obj.images = [] - elif hasattr(obj, "images") and obj.images is None: - obj.images = [] - return super().model_validate(obj, **kwargs) + return [] + if v is None: + return [] + return v # ============================================================