Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 !

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)


Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading