Home > OS >  Short way to get all field names of a pydantic class
Short way to get all field names of a pydantic class

Time:02-27

Minimal example of the class:

from pydantic import BaseModel

class AdaptedModel(BaseModel):
    def get_all_fields(self, alias=False):
        return list(self.schema(by_alias=alias).get("properties").keys())

class TestClass(AdaptedModel):
    test: str

The way it works:

dm.TestClass.get_all_fields(dm.TestClass)

Is there a way to make it work without giving the class again?

Desired way to get all field names:

dm.TestClass.get_all_fields()

It would also work if the field names are assigned to an attribute. Just any way to make it make it more readable

CodePudding user response:

Okay the solution is to use a class-method instead of an instance method:

from pydantic import BaseModel, Field

class AdaptedModel(BaseModel):
    @classmethod
    def get_field_names(cls,alias=False):
        return list(cls.schema(alias).get("properties").keys())

class TestClass(AdaptedModel):
    test: str = Field(alias="TEST")

We are using Python 3.6.8 and apparently it was already introduce. For completeness sake can somebody comment since when @classmethod exists? I assume since 3.6.

  • Related