[Python] How to create instance of a Pydantic model with subset fields

Discussão em 'Python' iniciado por Stack, Dezembro 18, 2024.

  1. Stack

    Stack Membro Participativo

    This is the model

    class UsersInformationModel(BaseDataModel):
    id: Optional[int] = None
    is_vip: bool = False
    creation_tag: Optional[dict] = None # JSON field mapped to a dictionary
    user_id: int # Not nullable
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None
    branch_id: Optional[int] = None
    setting: Optional[dict] = None # JSON field mapped to a dictionary
    vip_type: int = 0
    medication_history: Optional[bool] = None
    other_disease: Optional[str] = None
    tobacco_alcohol_use: Optional[bool] = None
    consumed_medications: Optional[str] = None
    consumed_medications_amount: Optional[str] = None


    and BaseDataModel

    from pydantic import BaseModel, PrivateAttr, root_validator
    from typing import Dict, Any


    class BaseDataModel(BaseModel):
    _explicit_fields: set = PrivateAttr(default_factory=set)

    class Config:
    # Pydantic settings
    populate_by_name = True
    exclude_unset = True

    @root_validator(pre=True)
    def validate_fields(cls, values):
    # This ensures that only explicitly set fields are retained in the model
    for field in values.copy():
    if field not in cls.__fields__:
    del values[field]
    return values

    def dict(self, **kwargs):
    # Ensure fields are excluded if not set (only non-None fields are included)
    return super().model_dump(exclude_unset=True, **kwargs)


    The problem is when I write:

    data = {
    'user_id': self.current_user.id,
    'medication_history': self.data.medication_history,
    'other_disease': self.data.other_disease,
    'tobacco_alcohol_use': self.data.tobacco_alcohol_use,
    'consumed_medications': self.data.consumed_medications,
    'branch_id': None,
    'consumed_medications_amount': self.data.consumed_medications_amount,
    }
    data = UsersInformationModel(**data)
    data_dict = data.dict()


    The data contains all of the model's fields and sets the non-mentioned fields to None, but the data_dict is OK and only contains fields included in the data.

    How can I change BaseDataModel so that data only contains the mentioned fields? No matter if the value is None, I want it to have only explicitly included fields.

    Continue reading...

Compartilhe esta Página