[Python] Getting error related to lazy loading when adding many to many relationship

Discussão em 'Python' iniciado por Stack, Dezembro 19, 2024.

  1. Stack

    Stack Membro Participativo

    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="me@email.com", 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.

    Continue reading...

Compartilhe esta Página