Is this concept somehow possible in Pydantic:
## one file
class StatusOut(BaseModel):
id: int
name: str
## another file
class UserOut(BaseModel):
name: str
status_name: StatusOut.name ## IS THIS ACHIEVABLE???
I get an error "AttributeError: type object 'StatusOut' has no attribute 'name'"
So the first and only thing I got in mind is to override validation with @validator(...) decorator.
from pydantic import BaseModel, validator
class StatusOut(BaseModel):
id: int
name: str
class UserOut(BaseModel):
name: str
status_name: StatusOut
@validator("status_name")
def redefine_status_name(cls, v):
return v.name
status = StatusOut(id=1, name="status")
user = UserOut(name="test", status_name=status)
print(user.json()) # {"name": "test", "status_name": "status"}
I guess there is no need to explain what I did, I just returned StatusOut().name instead of StatusOut itself
Although I do not suggest doing that, as it makes status_name's real type not the one that is declared and might confuse you in future