The direct assignment to the forward side of a many-to-many set is not allowed. Instead, it is recommended to use the products.set() method for assigning values.
아래와 같이 출력해주는 Schema를 그냥 ModelSchema를 통해 자동으로 생성해 낼 수 있다.
class config: 부분을 살펴보면, 원하는 테이블을 model=테이블명 형태로 정의 하고 있다.
class FirmwareOutSchema(ModelSchema):
# option field 혹은 None 값을 가지고 있는 필드의 경우, 아래 처럼 미리 선언해서 None이라도 대입해둬야 한다.
desc: str = None
# manytomany 필드의 경우 아예 해당 테이블의 out schema 로 정의해 두면, 아래 스키마에 맞게 데이터를 다 가져온다.
products: List[ProductOutSchema] = None
class Config:
model = Firmware
# model_fields = ['id', 'username', 'first_name', 'last_name']
model_exclude = ["updated_at", "created_at"]
필드값들 중에 None 이나 NULL 이 들어 있으면 아래와 같은 에러가 발생하기도 한다.
File "pydantic\main.py", line 579, in pydantic.main.BaseModel.from_orm
pydantic.error_wrappers.ValidationError: 1 validation error for NinjaResponseSchema
response -> items -> 0 -> desc
none is not an allowed value (type=type_error.none.not_allowed)
사실 None 같은 값이 들어 있을 수도 있는데 에러를 띄우는 것을 예상하지 못했다. 그래서 귀찮아도 옵션필드들은
Out Schema 정의할때 동일한 필드명의 변수를 선언하고, 기본 값을 넣어 주도록 하자.