Reputation: 1184
For some reason I get a foreign key error when a I try to link a certain aspect of my Actions table with my contacts table. The error I get is:
sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship Contacts.actions - there are multiple foreign key paths linking the tables. Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference to the parent table.
I need help understanding why the already linked table doesnt apply to the second attribute. (see line surrounded by comments in code below)
My Declarative Code:
Base = declarative_base()
class Users(Base):
__tablename__ = 'users'
# Here we define columns for the table person
# Notice that each column is also a normal Python instance attribute.
id = Column(Integer, primary_key=True)
username = Column(String(30), nullable=False)
first_name = Column(String(20), nullable=False)
last_name = Column(String(20), nullable=False)
email = Column(String(40), nullable=False)
phone = Column(String(10), nullable=False)
#default_duration = Column(Integer(2))
class Actions(Base):
__tablename__ = 'actions'
id = Column(Integer, primary_key=True)
action = Column(String(15), nullable=False)
message = Column(String(140), nullable=False)
duration = Column(Integer(2), nullable=False)
class Contacts(Base):
__tablename__ = 'contacts'
# Here we define columns for the table address.
# Notice that each column is also a normal Python instance attribute.
id = Column(Integer, primary_key=True)
contact_name = Column(String(30), nullable=False)
time_of_last_message = Column(String(40))
message_log = Column(String(450))
users_id = Column(Integer, ForeignKey('users.id'), nullable=False)
users = relationship(Users)
##############################
#### If this line is commented it out, it works
#### But If it is present I get the error
actions_action = Column(String, ForeignKey('actions.action'))
####
###############################
actions_id = Column(Integer, ForeignKey('actions.id'))
actions = relationship(Actions)
Upvotes: 0
Views: 1306
Reputation: 20548
Because, as the error message says, you have multiple foreign keys between Contacts
and Actions
, namely actions_id
and actions_action
, so it doesn't know which one you want to use for the relationship actions
. You can fix it by specifying (again, as the error message suggests) foreign_keys
:
actions = relationship(Actions, foreign_keys=actions_id)
This fixes the error, but a better question would be why you would need actions_action
in addition to actions_id
?
Upvotes: 1