1

I am working on a small Python CRUD game using FastAPI. For personal reasons, I don't want to use an ORM and I am using psycop2 as a db connector and pydantic for schemas validation (for any CRUD operations).

models/villages.py

from pydantic import BaseModel


class Village(BaseModel):

    village_id: int
    name: str
    owner_id: int
    location_id: int


class UserVillages(BaseModel):

    villages: list[Village]

crud/villages.py

def get_villages(session: Database, user_id: str):
    sql = """
        SELECT *
        FROM villages 
        WHERE owner_id = (%s)
        """
    params = [user_id]
    records = session.select_rows_dict_cursor(sql, params)
    print(records) ## [[1, 'paris', 145, 4, 41], [3, 'milan', 16, 4, 15]]
    

Instead of printing records, I would like to convert all of my dictRow into a Village object and all Villages into a UserVillages village object. Would it be posible to do that without a lop of extra data structure and loops?

**I found a way to do it but it's not really efficient and there is probably build-in functions to do it **

def get_villages(session: Database, user_id: str):
    sql = """
        SELECT *
        FROM villages 
        WHERE owner_id = (%s)
        """
    params = [user_id]
    records = session.select_rows_dict_cursor(sql, params)
    villages = []
    for record in records:
        villages.append(
            Village(
                village_id=record[0],
                name=record[1],
                owner_id=record[2],
                location_id=record[3],
            )
        )
    return UserVillages(villages=villages)
Pierre-Alexandre
  • 543
  • 1
  • 10
  • 31
  • Does your column names in the table match the pydantic field names? – MatsLindh May 02 '22 at 07:01
  • they do, at least the ones I have selected in my query – Pierre-Alexandre May 02 '22 at 07:36
  • 1
    In that case you should be able to do `return UserVillages(villages=parse_obj_as(List[Village], records))` as shown in https://stackoverflow.com/a/61021183/137650 `parse_obj_as` is a utility function under `pydantic` – MatsLindh May 02 '22 at 08:28

0 Answers0