我有一个包含许多字段的模型,这些字段可以具有 None 值。 Pydantic (v2) 提供了做两件事的简单方法
model_dump
参数调用 include
时才包含某些字段。None
参数设置为 exclude_none
,不包含具有
True
如何确保包含某些(但不包括其他)字段,即使它们具有
None
值?如果我同时包含 exclude_none
和 include
参数,则排除部分获胜。
以下单元测试将失败
import unittest
from pydantic import BaseModel
class A(BaseModel):
a: str | None
class PydanticIncludeAndExcludedNoneTestCase(unittest.TestCase):
""" Shows that `exclude_none` wins over `include` when dumping the pydantic v2 model """
def test_simple(self):
item = A(a=None)
d = item.model_dump(include={'a'}, exclude_none=True)
self.assertEqual(d['a'], None) # add assertion here
if __name__ == '__main__':
unittest.main()
这是您需要的吗?
from pydantic import BaseModel, model_serializer
class A(BaseModel):
a: str | None
b: str | None
@model_serializer(mode="wrap")
def _serialize(self, handler):
d = handler(self)
d['a'] = self.a
return d
a1 = A(a=None, b=None)
a2 = A(a="strrrr", b=None)
print(a1.model_dump(exclude_none=True))
print(a2.model_dump(exclude_none=True))
输出:
{'a': None}
{'a': 'strrrr'}
或者您可以修改它以将必填字段列表作为模型的参数:
from pydantic import BaseModel, model_serializer
class A(BaseModel):
a: str | None
b: str | None
c: int | None
_always_serialize_fields: list["str"] = ["a", "c"]
@model_serializer(mode="wrap")
def _serialize(self, handler):
d = handler(self)
for f in self._always_serialize_fields:
d[f] = getattr(self, f)
return d
a1 = A(a=None, b = None, c=None)
a2 = A(a="strrrr", b=None, c=None)
print(a1.model_dump(exclude_none=True))
print(a2.model_dump(exclude_none=True))
输出:
{'a': None, 'c': None}
{'a': 'strrrr', 'c': None}