You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pydantic-redis添加dict/List类型字段验证失败,求排查原因

问题原因与解决方案

你遇到的问题是因为pydantic-redis对dict、List这类复杂类型没有默认的自动序列化/反序列化逻辑,而int、str等基础类型有内置处理逻辑,所以不会报错。

要解决这个问题,有两种常用方式:

方法一:使用pydantic的Json类型定义字段

通过Json类型包裹复杂类型,让pydantic自动处理序列化和反序列化:

from datetime import date
from pydantic import Json
from typing import List
from pydantic_redis import Model, Store, RedisConfig

class Book(Model):
    _primary_key_field: str = 'title'
    title: str
    author: str
    published_on: date
    in_stock: bool = True
    # 定义dict类型字段
    new_field: Json[dict] = {}
    # 如果是List[int]类型:
    # new_field: Json[List[int]] = [8]

# 后续的Store初始化和操作保持不变
redis_config = RedisConfig(db=0, host="localhost", port=6379)
store = Store(name="book_store", redis_config=redis_config, models=[Book])

方法二:自定义序列化器

如果需要更灵活的控制,可以给模型指定自定义的序列化和反序列化方法:

from datetime import date
from typing import List
from pydantic_redis import Model, Store, RedisConfig
import json

class Book(Model):
    _primary_key_field: str = 'title'
    title: str
    author: str
    published_on: date
    in_stock: bool = True
    new_field: dict = {}

    @classmethod
    def _serialize(cls, data):
        # 对new_field单独序列化
        data["new_field"] = json.dumps(data["new_field"])
        return super()._serialize(data)

    @classmethod
    def _deserialize(cls, data):
        data = super()._deserialize(data)
        # 反序列化new_field
        data["new_field"] = json.loads(data["new_field"])
        return data

# 后续Store初始化和操作不变

推荐优先使用方法一,更简洁且符合pydantic的设计规范。

内容的提问来源于stack exchange,提问作者David Wahlstedt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 17:57:27