1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Pydantic Date Field Serialization

Discussão em 'Python' iniciado por Stack, Outubro 5, 2024 às 19:42.

  1. Stack

    Stack Membro Participativo

    Using Pydantic V2, is there a way to specify the date format to use for serialization for any date field in a model? For context, I have a base model class, let's call it CustomBaseModel, and it inherits from Pydantic's BaseModel. I want to be able to specify a universal format for serializing any date fields in the child class models. Because CustomBaseModel will have many child classes, I can't just just use "@field_serializer" because the fields are not defined in the base class. I am currently able to do this using the json_encoders kwarg of the model's ConfigDict but this is deprecated and will be removed in the future. I tried doing it with "@model_serializer" but then the alias generators are bypassed. I am curious to hear what others may have done to achieve this. I suppose I could manually call the alias generator on each field in the "@model_serializer" function but I am hoping there is a cleaner way to do this.

    class CustomBaseModel(BaseModel):
    # specify the date format here
    pass

    class ChildClassModel(CustomBaseModel):
    created_at: date
    updated_at: date
    # I want these dates, and date fields on any other model that inherits from
    # CustomBaseModel, to all be serialized as %Y-%m-%d

    Continue reading...

Compartilhe esta Página