0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

pydantic で alias

Posted at

概要

pydantic の BaseModel で dict との入/出力のキー名とプロパティ名を変える方法をメモ。

方法

class A(BaseModel):
  # これで bbb というキーで出力されるようになる。aaa というキーは出力されない
  aaa: int = Field(..., alias='bbb')

  class Config:
    # これで bbb というキーも入力で受け付けるようになる。
    allow_population_by_field_name = True

応用編

class AliasBaseModel(BaseModel):
  # _ から始まっているフィールドは入出力対象外
  _field_to_alias = {}

  def __init_subclass__(cls, **kwargs):
    super().__init_subclass__(**kwargs)
    for f, a in cls._field_to_alias.items():
      if f in cls.__annotations__:
        # noinspection PyUnresolvedReferences
        cls.__fields__[f].field_info.alias = a

  class Config:
    allow_population_by_field_name = True


class Parent(AliasBaseModel):
  aaa: int = 1

# 親のプロパティ名を変更できる。(内部的には aaa のままだが入出力は bbb になる。)
class Child(Parent):
  _field_to_alias = {
    'aaa': 'bbb',
  }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?