Home > Software design >  I want to validaton condition for two fields Pydantic
I want to validaton condition for two fields Pydantic

Time:11-19

The task is to make a validator for two dependent fields. If MCC is not empty, then you need to check that OUTSIDE is passed in the type field. And vice versa. If MCC is empty, then INSIDE should be passed in the type field.

I wrote this code, but it doesn't work. Can someone tell me the best way to do this

import json

from pydantic.dataclasses import dataclass, ValidationError
from pydantic import root_validator, validator
from typing import Union, List, Literal


@dataclass
class DataInclude:
    type: Literal['INSIDE', 'OUTSIDE']
    accountID: Union[None, int]
    date: int
    tranDate: int
    operationType: Literal['CREDIT', 'DEBIT', 'OPEN', 'DV']
    paymentDetailType: Literal[
        'BETWEEN_THEIR', 'INSIDE_BANK', 'EXTERNAL_INDIVIDUAL', 'EXTERNAL_ENTITY', 'OTHER_BANK',
        'HOUSING_AND_COMMUNAL_SERVICE', 'MOBILE', 'INTERNET', 'TRANSPORT', 'TAX_AND_STATE_SERVICE',
        'NOT_FINANCE', 'CONTACT_ADDRESSLESS', 'DIRECT', 'SFP', 'OUTSIDE_CASH', 'INSIDE_OTHER',
        'OUTSIDE_OTHER', 'C2B_PAYMENT', 'INSIDE_DEPOSIT']
    amount: Union[int, float, None]
    documentAmount: Union[int, float, None]
    comment: str
    documentID: int | None
    accountNumber: str
    currencyCodeNumeric: int
    merchantName: str | None
    merchantNameRus: str | None
    groupName: str
    md5hash: str
    svgImage: str | None
    fastPayment: str | None
    terminalCode: str | None
    deviceCode: str | None
    country: str | None
    city: str | None
    operationId: str | None
    isCancellation: bool | None  # BOOL!
    cardTranNumber: str | None
    opCode: int | None
    MCC: int | None
    
    @validator('type', 'MCC')
    def check_passwords_match(cls, values):
        type_operation, mcc = values['type'], values['MCC']
        if mcc is not None:
            if type_operation != "OUTSIDE":
                raise ValueError('MCC NOT EQUAL TYPE OPERATION')
        return values


@dataclass
class MessageResponse:
    statusCode: int
    errorMessage: Union[None, str]
    data: List[DataInclude]

    @staticmethod
    def validation_body(data):
        try:
            data_new = json.loads(data)
            MessageResponse(**data_new)
            return True
        except ValidationError as e:
            raise e

I have tried various options. I have read the documentation, but could not find the answer to my question. I use pydantic for automation api testing

CodePudding user response:

I think you are looking for this, the validator on MCC will have to deal with both your cases.

    @validator("MCC")
    def check_passwords_match(cls, v, values):
        if "type" not in values:
            raise ValueError("TYPE VALIDATION FAILED")
        if (v is not None and values["type"] != "OUTSIDE") or (
            v is None and values["type"] != "INSIDE"
        ):
            raise ValueError("MCC NOT EQUAL TYPE OPERATION")
        return v
  • Related