Minimal example of the class:
JavaScript
x
9
1
from pydantic import BaseModel
2
3
class AdaptedModel(BaseModel):
4
def get_all_fields(self, alias=False):
5
return list(self.schema(by_alias=alias).get("properties").keys())
6
7
class TestClass(AdaptedModel):
8
test: str
9
The way it works:
JavaScript
1
2
1
dm.TestClass.get_all_fields(dm.TestClass)
2
Is there a way to make it work without giving the class again?
Desired way to get all field names:
JavaScript
1
2
1
dm.TestClass.get_all_fields()
2
It would also work if the field names are assigned to an attribute. Just any way to make it make it more readable
Advertisement
Answer
What about just using __fields__
:
JavaScript
1
10
10
1
from pydantic import BaseModel
2
3
class AdaptedModel(BaseModel):
4
parent_attr: str
5
6
class TestClass(AdaptedModel):
7
child_attr: str
8
9
TestClass.__fields__
10
Output:
JavaScript
1
3
1
{'parent_attr': ModelField(name='parent_attr', type=str, required=True),
2
'child_attr': ModelField(name='child_attr', type=str, required=True)}
3
This is just a dict and you could get only the field names simply by: TestClass.__fields__.keys()
See model properties: https://pydantic-docs.helpmanual.io/usage/models/#model-properties