Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate and apply an unique value to a field from a pydantic model each time an object is initialized

I'm making a model using pydantic and I'd like to declare a field which gen a random value (like an id) every time an object is created. I don't want to have to pass the value of that field when initializing the object, here is a quick example of what i want using python class method:

from uuid import uuid4

class User:
    def __init__(self, name, last_name, email):
        self.name = name
        self.last_name = last_name
        self.email = email
        self.id = uuid4()

I've tried making it that way with pydantic:

from pydantic import BaseModel, EmailStr
from uuid import UUID, uuid4


class User(BaseModel):
    name: str
    last_name: str
    email: EmailStr
    id: UUID = uuid4()

However, all the objects created using this model have the same uuid, so my question is, how to gen an unique value (in this case with the id field) when an object is created using pydantic. Thanks !

like image 482
ketabreader Avatar asked Sep 17 '25 13:09

ketabreader


1 Answers

you can do like this


from pydantic import BaseModel, EmailStr, Field
from uuid import UUID, uuid4


class User(BaseModel):
    name: str
    last_name: str
    email: EmailStr
    id: UUID = Field(default_factory=uuid4)


like image 152
mxp-xc Avatar answered Sep 20 '25 03:09

mxp-xc