Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to autogenerate Pydantic field value and not allow the field to be set in initializer or attribute setter

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.

like image 231
Brian Avatar asked Sep 02 '25 16:09

Brian


1 Answers

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())
like image 59
Paweł Rubin Avatar answered Sep 05 '25 06:09

Paweł Rubin