python
config_error
ai_generated
true
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%Fix Rate
87%Confidence
0Evidence
2024-07-08First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 2.x | active | — | — | — |
Root Cause
Decorator order was reversed: @computed_field placed above a plain method without @property, or @property placed above @computed_field.
generic中文
装饰器顺序颠倒:@computed_field 放在了没有 @property 的普通方法之上,或 @property 放在了 @computed_field 之上。
Workarounds
-
95% success
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% success
from pydantic import model_serializer class M(BaseModel): a: int @model_serializer def ser(self): return {'a': self.a, 'double': self.a * 2}
Dead Ends
Common approaches that don't work:
-
60% fail
Field no longer appears in model_dump / JSON output.
-
55% fail
staticmethod returns a descriptor; validation raises because it is not a property.
-
50% fail
Recomputes only at construction; stale if inputs mutate.