1

I have 3 files for Pydantic models. In each file there is a reference to a model from a different file which is creating a circular dependency. I have these circular dependencies since I want to have embedded data in the API responses which maybe ultimately is my root issue but I believe what I want to achieve at the moment is possible and I want to know how.

I've also tried importing some of the models to the main.py but now that these 3 models are so interdependent I think that solution has stopped working, besides it felt kinda hacky anyways so I didn't like doing that.

I linked a similar issue below, but the recommendations from that question are not helping me. Plus, there may be developments from 2 years ago that I'm not aware of.

Below are the simplified models I'm working with.

# user models
class UserSchema(BaseSchema):
    id: uuid.UUID


CheckinSchema = ForwardRef("CheckinSchema")


class UserSchemaDetails(UserSchema):
    latest_checkin: Optional[CheckinSchema]


from app.schemas.checkin import CheckinSchema
UserSchemaDetails.update_forward_refs()
# checkin models
UserSchema = ForwardRef("UserSchema")
NakamalSchema = ForwardRef("NakamalSchema")


class CheckinSchema(CheckinSchemaBase):
    id: uuid.UUID
    user: UserSchema
    nakamal: NakamalSchema


from app.schemas.user import UserSchema
from app.schemas.nakamal import NakamalSchema
CheckinSchema.update_forward_refs()
# nakamal models
UserSchema = ForwardRef("UserSchema")


class NakamalSchema(NakamalSchemaBase):
    id: uuid.UUID
    chief: Optional[UserSchema] = None


from app.schemas.user import UserSchema
NakamalSchema.update_forward_refs()

Similar issue: How to correctly structure pydantic models?

Mike T
  • 43
  • 4

1 Answers1

0

There was (are still?) ongoing issues on the Pydantic and FastAPI github repos about this very question. Supporting a 3 way import is not possible which I find frustrating since other packages such as Marshmallow or SQLAlchemy handle these situation easily.

As a dirty solution I had to make a minimal schema within the module I was working to avoid imports and leave a comment to keep both the local schema and the original full schema up-to-date with each other.

Mike T
  • 43
  • 4