I’m struggling with SQLAlchemy. I have a model with a many to many relationship set up:
class User(Base):
roles: Mapped[List["Role"]] = relationship(
secondary="user_roles", back_populates="users"
)
I’m setting up some code to populate the database with test data:
user = await register_user(
email="[email protected]", username="username", password="test1234"
)
db_session.add(user)
await db_session.commit()
admin_role = Role(name="Admin", owner_id=user.id)
db_session.add(admin_role)
user.roles.append(admin_role)
db_session.add(user)
await db_session.commit()
But when I do this, I get
sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected place?
There’s a link with that error which suggests that the problem is lazyloading. But in this case, I didn’t load anything. I’m confused as to how to establish the cross model relationship.
Probably referencing user.id
because user is expired on commit. I think appending the role should be sufficient after adding. This can be configured by toggling expire on commit.
You can try this:
user = await register_user(
email="[email protected]", username="username", password="test1234"
)
db_session.add(user)
await db_session.commit()
admin_role = Role(name="Admin")
db_session.add(admin_role)
user.roles.append(admin_role)
await db_session.commit()