Models and Schemas

To make full use of FastAPI, Pony’s models have to work with Pydantic’s schemas. Unfortunately, this requires somewhat duplicate model definitions. We’re following FastAPI’s example here.

Here are the Pony models from Getting Started with Pony:

  1. class Person(db.Entity):
  2. name = Required(str)
  3. age = Required(int)
  4. cars = Set('Car')
  5. class Car(db.Entity):
  6. make = Required(str)
  7. model = Required(str)
  8. owner = Required(Person)

We want to expose Person in FastAPI like this:

  1. @api.get('/persons')
  2. async def read_all_persons():
  3. with db_session:
  4. persons = Person.select()
  5. result = [PersonInDB.from_orm(p) for p in persons]
  6. return result
  7. @api.get('/person/{pid}')
  8. async def read_single_person(pid: int):
  9. with db_session:
  10. person = Person[pid]
  11. result = PersonInDB.from_orm(person)
  12. return result

For this, we can write the following Pydantic schemas:

  1. class CarOut(BaseModel):
  2. make: str
  3. model: str
  4. class PersonInDB(BaseModel):
  5. name: str
  6. age: int
  7. cars: List[CarOut]
  8. @validator('cars', pre=True, allow_reuse=True)
  9. def pony_set_to_list(cls, values):
  10. return [v.to_dict() for v in values]
  11. class Config:
  12. orm_mode = True

Without preparation, Pony’s related objects aren’t interpreted correctly. Use a validator to make them accessible for Pydantic.