'using nested classes for organize Model, how to "crossreference"
I'm want to use nested classes to organize my pydantic models. So something like this:
class AttributeValue(BaseModel):
id: int
typeid: int
value: str
class AttributeValueAddRequest(BaseModel):
typeid: int
value: str
class AttributeType(BaseModel):
id: int
name: str
type: Literal['a', 'b', 'c']
values: list[AttributeValue] = None
extra: bool = False
class AttributeTypeAddRequest(BaseModel):
name: str
type: Literal['a', 'b', 'c']
extra: bool = False
[...]
This is just a small example. But the amount of code grows and it became (in my opinion) very unreadable. So I though, it could be nice to organize this in nested classes:
class MAttribute:
class Value:
class Entry(BaseModel):
id: int
typeid: int
value: str
class AddRequest(BaseModel):
typeid: int
value: str
class Type:
class Entry(BaseModel):
id: int
name: str
type: Literal['a', 'b', 'c']
values: list[Value.Entry] = None <-- How to reference?
extra: bool = False
class AddRequest(BaseModel):
name: str
type: Literal['a', 'b', 'c']
extra: bool = False
Attribute=MAttribute()
So if I want to create a Value-Entry model from a dict i use:
model=Attribute.Value.Entry.parse_obj(**dict)
This works as expected. My problem is now, that I do not know how to reference the values in in Type.Entry model to Value.Entry. I tried it with lambda, etc.. But no luck (or I didn't understand it right).
So how can I do this? Or is there a better way to organize the models and don't have everything in a single class from top to bottom (like in the first code block)?
Regards.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|