4

Is there any way to use multiple field alias without using root_validator?

My current code is this:

class GetInfo(BaseModel):
    name: str = Field(alias='name1')
    name2: str = Field(alias='name2')
    
    @root_validator
    def format_name(cls, values):
        if values['name'] is None:
            if values['name2'] is not None:
                values['name'] = values['name2']
            return values
        return None

The name1 field is sometimes empty while the name2 field is mostly not empty I wanted to use the name2 if the name1 is really empty.

Or can you suggest better way than what I did?

mark12345
  • 233
  • 1
  • 4
  • 10

2 Answers2

2

Pydantic V1:

Short answer, you are currently restricted to a single alias. (In other words, your field can have 2 "names".) If you want additional aliases, then you will need to employ your workaround.

Pydantic V2:

Pydantic V2 introduces "more powerful alias(es)":

class GetInfo(BaseModel):
    name: str = Field(validation_alias=AliasChoices('name1', 'name_1', 'name_one'))
    name2: str = Field(validation_alias=AliasChoices('name2', 'name_2', 'name_two'))


# The following will all be equal
assert all((
    GetInfo(name1="Sam", name2="Colvin"),
    GetInfo(name_1="Sam", name_2="Colvin"),
    GetInfo(name_one="Sam", name_two="Colvin"),
))
Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69
1

if anyone is wondering, here is a working solution with pydantic v2

import pydantic
print(pydantic.__version__ )  # 2.1.0 
from pydantic import BaseModel, Field, AliasChoices
class User(BaseModel):
    first_name: str = Field(validation_alias=AliasChoices('first_name', 'fname'))
print(User(first_name="Sam"))
print(User(fname="toto"))
infinity911
  • 201
  • 1
  • 9