Skip to content
Advertisement

Why am I getting AmbiguousForeignKeysError?

I’ve run into an issue after following the SqlAlchemy guide here.

Given the following simplified module:

JavaScript

That I am attempting to build a query using:

JavaScript

Why am I getting the following error?

JavaScript

I was pretty sure I’d specified the two foreign key relationships?


Update:

I’ve tried the following combination as I think has been suggested in the comments but got the same error:

JavaScript

Update 2:

Added some details on what the output should look like:

player table:

JavaScript

match_result table:

JavaScript

Query output:

JavaScript

Advertisement

Answer

The two-way relationship and multiple join paths prevent SQLAlchemy from automatically determining the joins, and the relationships in both tables emit very similar error messages makes it difficult to understand where the problems lie (and whether a given change makes any progress in solving them). I found the simplest approach was to comment out the relationship in Player until MatchResult was working properly.

The changes to MatchResult are the same as those specified in the multiple join paths docs referenced in the question. To get the relationship in Player to work I specified the primary join condition so that SQLAlchemy could determine how to join to MatchResult.

JavaScript

Once these changes have been made, basic querying can be done without any explicit aliasing or joins.

JavaScript

The above code, for clarity and usefulness to other readers, does not include the inheritance, mixin and session management code that is specific to the OP’s application. Thiis version includes all of these.

JavaScript
Advertisement