Write one of model's attributes to the database and then read entire model from this single attribute

Question:

I am trying to create a Currency model that wraps pycountry‘s Currency object. This model will include the currency code and full name. However, I only want to store the code in my database when I call the model’s .dict() method. When this code is then read from the database, it should use pycountry to retrieve the full currency object and store the currency name in the model too.

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)

This prints:

name='United States of America' currency=Currency(code='USD', name='US Dollar')

Now I use country.dict() to write to my MongoDB database.

This looks like:

name                       | currency
-------------------------------------
'United States of America' | 'USD'

Now when I read this from the database, I want the object to be the same as when I printed it before, with currency populated as Currency(code='USD', name='US Dollar'), but when I do read this Country from the database, I am getting value is not a valid dict (type=type_error.dict).

How can I achieve this?

Asked By: KOB

||

Answers:

is that the result you want ?

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'}}
Answered By: Bastien B
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.