'Pydantic preparing data for validation

class CampaignData(BaseModel):
    title: NonEmptyString
    conversion: Conversion
    date: datetime.date
    name: NonEmptyString
    budget: PositiveDecimal


    @validator('date', pre=True)
    def format_date(cls, value: str) -> datetime.date:
        #some logic
            
            
    @validator('name')
    def check_name(cls, value: str) -> str:
        #some logic

        return value
        
        
    @root_validator
    def check_value_params_match(cls, values):
        #some logic

        return values
    
    

Incoming data example

{'campaigns': {'title': 'HS_GP', 'conversion': 'Buyer14', 'date': '22.04.21', 'name': 'HS_GP_UAC', 'budget': '2000'}}

How can I make input data be converted before @validator and @root_validator work, so that the value argument in all validators gets rid of the campaigns key?

{'title': 'HS_GP', 'conversion': 'Buyer14', 'date': '22.04.21', 'name': 'HS_GP_UAC', 'budget': '2000'}

Some thind like the function remove_key should be called at the very beginning

def remove_key(data):
    return data['campaigns']


Solution 1:[1]

It sounds like you only want to use the data that is inside campaigns.

The following should work:

data = {
    'campaigns': {
        'title': 'HS_GP',
        'conversion': 'Buyer14',
        'date': '22.04.21',
        'name':
        'HS_GP_UAC',
        'budget': '2000'
    }
}


class CampaignData(BaseModel):
    title: NonEmptyString
    conversion: Conversion
    date: datetime.date
    name: NonEmptyString
    budget: PositiveDecimal

    @validator('date', pre=True)
    def format_date(cls, value: str) -> datetime.date:
        #some logic

    # etc...

campaign_data = CampaignData.parse_obj(data['campaigns'])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Paul P