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 !
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)
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