D
D
domanskiy2021-06-23 09:03:15
Python
domanskiy, 2021-06-23 09:03:15

How to do validation using Pydantic with replacing a value from a dictionary?

I'm making a small parser.
There is yml (yml_catalog from 1C for Yandex with product descriptions)
Products from yml are parsed and loaded into woocommerce via API. There are no questions with this.
But there is a moment. The yml has key": "производитель".
Woocommerce has key": "производитель", but the list is different.
Now I just compare the value from yml to the value from woocommerce.
The question is, can this (value replacement) be done by running json through pydantic ???

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vlad Grigoriev, 2021-06-23
@domanskiy

with a live example it would be easier, but it is possible to process values ​​through @validator
Implementation example, of course, you can do more complex processing

from pydantic import BaseModel, validator

keys = {
    '1': 'one'
}


class User(BaseModel):
    name: str = ''
    key: str = ''

    @validator('key')
    def update_key(cls, value):
        return keys.get(value, value)


user_1 = User.parse_obj({'name': 'Test User', 'key': '1'})
user_2 = User.parse_obj({'name': 'Test User', 'key': '2'})

print(user_1)
print(user_2)

name='Test User' key='one'
name='Test User' key='2'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question