Replies: 1 comment 2 replies
-
This is one of the solutions. https://github.com/PelicanQ/fastapi-users-question/blob/main/db_models/user_model.py#L22 posts: Mapped[list["Post_DB"]] = relationship(init=False, lazy='selectin') I'm not familiar with sqlalchemy 1.4 or 2.0, but I see from your error I understand that I should use So I threw this question into google and looked for stack overflow to find the answer. I don't think it's too hard to find the answer to this problem. You should learn how to do the sqlalchemy relationship or you'll run into the same kind of problem when accessing data in a relationship. |
Beta Was this translation helpful? Give feedback.
-
My register route fails as soon as User has a relationship attribute.
I have a User which should have many Post's. If I define my UserRead Pydantic model/schema to include posts, FastAPI will try to load posts for the response. This fails since FastAPI Users uses async SQLAlchemy which cannot lazy load (no implicit IO). Specifically I am calling the
/auth/register
as when following the docs.These are my SQLAlchemy models:
and UserRead schema:
The following is raised upon calling POST
/auth/register
with data. This error is from an async SQLAlchemy load which then tries to lazily access an attribute which is not eagerly loaded. Thus excluding posts from UserRead, the framework won't try loading it.Error extracting attribute: MissingGreenlet: greenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected place?
So one possibility might be to specify eager load for every relationship on
User_DB
but why wouldn't the docs of FastAPI Users say this if it was the only way to make relationships work? It also forces eager loading on every relationship attribute we would wanna return.Q: How are relationships meant to be used with FastAPI Users? Thank you!
The included routes don't even work with a simple related model. Reproduce with this minimal repo I made.
Beta Was this translation helpful? Give feedback.
All reactions