I want to autogenerate an ID field for my Pydantic model and I don't want to allow callers to provide their own ID value. I've tried a variety of approaches using the Field
function, but the ID field is still optional in the initializer.
class MyModel(BaseModel):
item_id: str = Field(default_factory=id_generator, init_var=False, frozen=True)
I've also tried using PrivateAttr
instead of Field
, but then the ID field doesn't show up when I call model_dump
.
This seems like a pretty common and simple use case, but I can't find anything in the docs for how to accomplish this.
Use a combination of a PrivateAttr
field and a computed_field
property:
from uuid import uuid4
from pydantic import BaseModel, PrivateAttr, computed_field
class MyModel(BaseModel):
_id: str = PrivateAttr(default_factory=lambda: str(uuid4()))
@computed_field
@property
def item_id(self) -> str:
return self._id
print(MyModel().model_dump())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With