0

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.

Idel
  • 1
  • 1
  • 1
  • I'm not super familiar with automap_base but it might have a problem resolving this issue automatically. What version of SQLAlchemy are you using ? – Ian Wilson Jan 03 '23 at 21:24
  • Also could you try to post the database DDL for the table you are trying to automap? – Ian Wilson Jan 03 '23 at 22:37
  • I'm using SQLAlchemy 1.4 and I only receive an error when creating a circular reference, ie. writing to the db without correcting the automapping. I do not receive an error when querying it. – Ian Wilson Jan 03 '23 at 22:59

0 Answers0