How To Get Values From Nested Pydantic Classes?
class mail(BaseModel): mailid: int email: str class User(BaseModel): id: int name: str mails: List[mail] data = { 'id': 123, 'name': 'Jane Doe',
Solution 1:
It looks like you are trying to access the class rather than the instance.
Here's one way of doing it:
from pydantic import BaseModel
from typing import List
class Mail(BaseModel):
mailid: int
email: str
one_mail = {"mailid": 1, "email": "aeajhs@gmail.com"}
mail = Mail(**one_mail)
print(mail)
# mailid=1 email='aeajhs@gmail.com'
With that in place, let's adapt the User
model:
class User(BaseModel):
id: int
name: str
mails: List[Mail]
data = {
"id": 123,
"name": "Jane Doe",
"mails":[
{"mailid": 1, "email": "aeajhs@gmail.com"},
{"mailid": 2, "email": "aeajhsds@gmail.com"}
]
}
userobj = User(**data)
print(userobj.mails)
# [Mail(mailid=1, email='aeajhs@gmail.com'), Mail(mailid=2, email='aeajhsds@gmail.com')]
If you only need one of the email addresses, you need to specify which one, e.g.:
print(userobj.mails[0].email)
# aeajhs@gmail.com
In order to get a list of all email addresses, you need to iterate over the mails
, e.g.:
print([mail.email for mail in userobj.mails])
# ['aeajhs@gmail.com', 'aeajhsds@gmail.com']
An as a side note: Pydantic supports email string validation.
Solution 2:
The error
AttributeError: 'list' object has no attribute 'email'
means you are accessing an attribute of the mails
list, not mail
object.
You should pick the object from the list first using an index:
print(userobj.mails[0].email)
And, if you want every email of every mails
instance, do
print([mail.email for mail in userobj.mails])
Post a Comment for "How To Get Values From Nested Pydantic Classes?"