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

如何在Pydantic的dict方法中包含被排除的字段

解决方案

情况1:普通自定义类(无序列化框架依赖)

如果是你自己实现的字段排除逻辑(比如通过标记属性、重写__dict__或__iter__过滤字段),要让内置dict()包含被标记为excluded=True的字段,只需调整过滤逻辑:

示例1:修改__dict__属性

假设你之前通过重写__dict__来排除字段,现在调整为保留标记字段:

class MyClass:
    def __init__(self):
        self.normal_field = "test"
        self.excluded_field = 123
        # 自定义排除标记
        self.excluded_field._excluded = True

    @property
    def __dict__(self):
        # 移除过滤条件,返回所有属性
        return super().__dict__
        # 若需区分内部/外部调用,可根据上下文调整:
        # if is_internal_call():
        #     return super().__dict__
        # else:
        #     return {k: v for k, v in super().__dict__.items() if not hasattr(v, '_excluded')}

示例2:重写__iter__方法

dict(obj)会迭代对象的键生成字典,重写__iter__返回所有属性键即可:

class MyClass:
    def __init__(self):
        self.normal_field = "test"
        self.excluded_field = 123

    def __iter__(self):
        # 返回所有属性的键
        yield from self.__dict__.keys()

调用dict(MyClass())就会包含excluded_field。

情况2:使用序列化框架(以Pydantic为例)

如果你的类是Pydantic模型,字段通过Field(exclude=True)标记为排除,默认dict()会过滤该字段,可通过两种方式让它被包含:

方式1:调用dict()时显式覆盖排除规则

直接传入exclude=None,强制包含所有字段:

from pydantic import BaseModel, Field

class MyModel(BaseModel):
    normal_field: str
    excluded_field: int = Field(exclude=True)

model = MyModel(normal_field="hello", excluded_field=456)
# 包含被排除字段的字典
full_dict = model.dict(exclude=None)

方式2:重写模型的dict()方法

如果希望默认调用dict()就包含该字段,可重写方法强制忽略排除设置:

from pydantic import BaseModel, Field

class MyModel(BaseModel):
    normal_field: str
    excluded_field: int = Field(exclude=True)

    def dict(self, **kwargs):
        # 强制覆盖exclude参数,确保包含所有字段
        kwargs["exclude"] = None
        return super().dict(**kwargs)

# 直接调用就会包含excluded_field
model = MyModel(normal_field="hello", excluded_field=456)
print(model.dict())  # {'normal_field': 'hello', 'excluded_field': 456}

核心逻辑

内置dict()对自定义对象的处理逻辑是:

  1. 如果对象实现了__iter__,则迭代生成键,再通过obj[key]取值;
  2. 否则直接使用对象的__dict__属性(即实例的属性字典)。

只要确保目标字段存在于__dict__中,或者被__iter__返回,dict()就会包含它。

内容的提问来源于stack exchange,提问作者Jhonathan Mizrahi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 05:03:17