[Python] Why won't Pydantic print the id as "_id"?

Discussão em 'Python' iniciado por Stack, Junho 19, 2025.

  1. Stack

    Stack Membro Participativo

    from pydantic import BaseModel,Field, UUID1
    from uuid import uuid1

    class myown(BaseModel):
    id: UUID1 = Field(default_factory=uuid1, alias="_id")
    name: str


    body = {"name": "skanda"}

    data = myown(**body)

    print(data.model_dump())


    Hi everyone, I have been wanting to have my own id for a class, and I wanted to dump this into MongoDB. So when I call data.model_dump(), I want it to convert the id field to _id. That way when I push it to Mongo, it will take my id that I have created instead of the one auto-created by Mongo.

    How do I do this? I have also tried using serialization_alias and alias. but they don't seem to work either.

    Continue reading...

Compartilhe esta Página