【发布时间】:2022-10-01 00:57:26
【问题描述】:
我正在尝试创建一个包装pycountry\'s Currency 对象的Currency 模型。该模型将包括货币代码和全名。但是,我只想在调用模型的.dict() 方法时将代码存储在我的数据库中。然后从数据库中读取此代码时,它应该使用pycountry 来检索完整的货币对象并将货币名称也存储在模型中。
import pycountry
from pydantic import BaseModel
class Currency(BaseModel):
code: str
name: str
def __init__(self, code: str):
currency = pycountry.currencies.get(alpha_3=code)
super().__init__(code=currency.alpha_3, name=currency.name)
def dict(self, **kwargs):
return self.code
class Country(BaseModel):
name: str
currency: Currency
country = Country(name=\"United States of America\", currency=Currency(\"USD\"))
print(country)
这打印:
name=\'United States of America\' currency=Currency(code=\'USD\', name=\'US Dollar\')
现在我使用country.dict() 写入我的MongoDB 数据库。
这看起来像:
name | currency
-------------------------------------
\'United States of America\' | \'USD\'
现在,当我从数据库中读取此内容时,我希望对象与之前打印时相同,currency 填充为Currency(code=\'USD\', name=\'US Dollar\'),但是当我从数据库中读取此Country 时,我得到了value is not a valid dict (type=type_error.dict)。
我怎样才能做到这一点?