python
config_error
ai_generated
true
pydantic.errors.PydanticUserError:@computed_field 应与 @property 搭配使用。当 @computed_field 应用于非属性时,会引发此错误。
pydantic.errors.PydanticUserError: @computed_field should be used with @property. This error is raised when a @computed_field is applied to a non-property.
ID: python/pydantic-computed-field-serialization
80%修复率
87%置信度
0证据数
2024-07-08首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 2.x | active | — | — | — |
根因分析
装饰器顺序颠倒:@computed_field 放在了没有 @property 的普通方法之上,或 @property 放在了 @computed_field 之上。
English
Decorator order was reversed: @computed_field placed above a plain method without @property, or @property placed above @computed_field.
解决方案
-
95% 成功率
from pydantic import BaseModel, computed_field class M(BaseModel): a: int b: int @computed_field @property def total(self) -> int: return self.a + self.b -
85% 成功率
from pydantic import model_serializer class M(BaseModel): a: int @model_serializer def ser(self): return {'a': self.a, 'double': self.a * 2}
无效尝试
常见但无效的做法:
-
60% 失败
Field no longer appears in model_dump / JSON output.
-
55% 失败
staticmethod returns a descriptor; validation raises because it is not a property.
-
50% 失败
Recomputes only at construction; stale if inputs mutate.