Search code examples
pythonmodel

Python pydantic model get field as string


From the code below, is there a way I can get name as string, not the value, but the field name itself?

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name = 'Jane Doe'

user = User(id='123', name='John')

Solution

  • You can get the list of fields via the __fields__ attribute:

    User.__fields__
    # or
    user.__fields__
    # {
    #     'id': ModelField(name='id', type=int, required=True),
    #     'name': ModelField(name='name', type=str, required=False, default='Jane Doe')
    # }
    

    and consequently, a list of the field names via:

    list(User.__fields__.keys()))
    # or
    list(user.__fields__.keys()))
    # ['id', 'name']