从下面的代码,有一种方法,我可以得到名称作为字符串,而不是值,但字段名称本身?
from pydantic import BaseModel
class User(BaseModel):
id: int
name = 'Jane Doe'
user = User(id='123', name='John')
您可以通过__fields__
属性获得字段列表:
User.__fields__
# or
user.__fields__
# {
# 'id': ModelField(name='id', type=int, required=True),
# 'name': ModelField(name='name', type=str, required=False, default='Jane Doe')
# }
,因此,通过:
获得一个字段名列表。list(User.__fields__.keys()))
# or
list(user.__fields__.keys()))
# ['id', 'name']
只是为了好玩)
class Job(BaseModel):
name: str
try: Job.name
except Exception as e:
field_name = str(e)