Idel
Idel

Reputation: 1

RecursionError on SQLAlchemy when using Loader options to eager load self referencial relationship

I am working with the following project: A CRUD for a system with dynamic models. To utilize SQL Alchemy ORM features, I am using automap_base to load the table models and be able to traverse the relationships and such.

In one particular case, I have a User table, which has a CreatedByUserId, UpdatedByUserId, and DeletedByUserId.

If I try to fetch a User with its CreatedByUser related model, using the following query:

Base = automap_base()
tables = Base.classes
model = (db.query(tables['User'])
        .options(
            joinedload(tables['User'].CreatedByUser)
        )
        .first())

I get a RecursionError: maximum recursion depth exceeded

Reading the documentation, what I guess happens is that SQLAlchemy enables eager loading for the User-CreatedByUser relationship for the entire query, so every time a User appears in the query, it fetches the CreatedByUser which results in an infinite loop. To be clear, what the optimal result would be is just the User model with a "CreatedByUser" attribute with the associated CreatedByUser model.

I tried adding a noload() or lazyload('*') at the end of the joinedload and using selectinload, subqueryload or immediateload with no luck.

.

Edit: After continuing to read SQLAlchemy documentation, I believe the error is due to the CreatedByUser being the same as the original. For example, having a user:

{
  id:3
  createdByUserId:3
}

However, I'm nowhere closer to finding a solution.

Upvotes: 0

Views: 455

Answers (0)

Related Questions