【问题标题】:Write one of model's attributes to the database and then read entire model from this single attribute将模型的属性之一写入数据库,然后从该单个属性中读取整个模型
【发布时间】: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)

我怎样才能做到这一点?

    标签: python pydantic


    【解决方案1】:

    那是你想要的结果吗?

    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)
    
    
    class Country(BaseModel):
        name: str
        currency: Currency
    
    
    country = Country(name="United States of America", currency=Currency("USD"))
    print(country)
    print(country.dict())
    
    
    name='United States of America' currency=Currency(code='USD', name='US Dollar')
    {'name': 'United States of America', 'currency': {'code': 'USD', 'name': 'US Dollar'}}
    

    【讨论】:

      猜你喜欢
      • 2020-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多