Creating objects with ID and populating other fields

Viewed 1542

I want to construct a Pydantic object only with ID, and then populate other fields based on ID.
I tried 2 different approaches, validator and also post init. Neither did work, so.

Common code:

from pydantic import BaseModel, validator

obj_list = [
    {'id': 1, 'name': 'a', 'desc': 'desc1'},
    {'id': 2, 'name': 'b', 'desc': 'desc2'},
    {'id': 3, 'name': 'c', 'desc': 'desc3'}
]

Solution 1:

class Obj(BaseModel):
    id: int
    name: str = None
    desc: str = None

    @validator('id')
    def validate_exists(cls, v):
        items = [h for h in obj_list if h['id'] == v]
        if len(items) == 0:
            raise ValueError('id doesnt exist')
        return v

    def __post_init__(self):
        item = [h for h in obj_list if h['name'] == v][0]
        self.name = item['name']
        self.desc = item['desc']

Obj(id=1)
# <Obj id=1 name=None desc=None>

Solution 2:

class Obj(BaseModel):
    name: str = None
    desc: str = None
    id: int

    @validator('id')
    def validate_exists(cls, v, values):
        items = [h for h in obj_list if h['id'] == v]
        if len(items) == 0:
            raise ValueError('id doesnt exist')
        item = items[0]
        values['name'] = item['name']
        values['desc'] = item['desc']
        return v

Obj(id=1)
# <Obj name=None desc=None id=1>

I feel like it's doable. I read both Pydantic's and FastApi's documentation, but couldn't find anything relevant to this. So, how can I construct objects using only IDs and then populate fields using DB or another object?

2 Answers

__post_init__ doesn't exist, I think you got that confused with dataclasses.

Pydantic things validation should happen once, when you create the model object. Though you can work around this by using Config.validate_assignment.

There are two solutions to this:

  1. Create each model with just id then use attribute assignment to set the other fields. This will be slower and I think is the wrong approach.
  2. Don't create the models until you have all the data you need to create the model. I would suggest this is the best approach.

I solved the problem using root_validator in pydantic.

from pydantic import BaseModel, root_validator

obj_list = [
    {'id': 1, 'name': 'a', 'desc': 'desc1'},
    {'id': 2, 'name': 'b', 'desc': 'desc2'},
    {'id': 3, 'name': 'c', 'desc': 'desc3'}
]
class Obj(BaseModel):
    id: int
    name: str = None
    desc: str = None

    @root_validator(pre=True)
    def validate_exists(cls, values):
        if 'id' not in values:
            raise ValueError("id doesn't exist in the fields")
        items = [h for h in obj_list if h['id'] == values['id']]
        if len(items) == 0:
            raise ValueError(f"there is no obj with id {values['id']}")
        return items[0]

Obj(id=1)
Related