Tortoise-orm, fastapi recursive models

Viewed 341

I am doing some POC work, and am porting some code from fastapi+sqlalchemy to fastapi+tortoise-orm.

I have some pydantic models which reference each other, sort of:

class DomainBase(BaseModel):
  id: int
  name: str

class Domain(DomainBase):
  mailboxes: List["MailboxSummary"] = []

class DomainSummary(DomainBase):
  mailboxes_count: int

class MailboxBase(BaseModel):
  id: int
  username: str

class Mailbox(MailboxBase):
  domain: DomainSummary

class MailboxSummary(MailboxBase):
  domain_id: int

This covers two DB models - Domain, and Mailbox, with a one-to-many relationship between them.

This works fine in sqlalchemy+fastapi - because the DB model and pydantic schema are defined completely separately, and as long as the db methods return objects with the right attributes, it all works fine.

With tortoise-orm+fastapi we use pydantic_model_creator which is based entirely on the DB, and doesn't seem to give me any opportunities to configure which pydantic model it should be using for a specific relation.

Is there a way to make this sort of thing work? It feels like using pydantic_model_creator is doing quite a lot of cross-contamination between the DB logic/schema and the presentation logic/schema, so I'd be very happy getting rid of it - but I'm not sure if tortoise-orm can be driven with pydantic without pydantic_model_creator..

0 Answers
Related