Search code examples
pythonmysqlsqlalchemy

Could not determine join condition on many to many association table


I'm trying to make a many to many association table, using this models.py and sqlalchemy

from sqlalchemy import Column, Integer, String, Numeric, Boolean, DateTime, Table, ForeignKey
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base 
Base = declarative_base()
cs_skin_case = Table('cs_skin_case', Base.metadata,
                    Column('cs_case_id', Integer, ForeignKey('cs_cases.id')),
                    Column('cs_skin_id', Integer, ForeignKey('cs_skins.id')))
class CS_SKINS(Base):
    __tablename__ = 'CS_SKINS'
    id = Column(Integer, primary_key=True)
    cs_cases = relationship("CS_CASES", secondary = cs_skin_case, back_populates= "cs_skins")
    
class CS_CASES(Base):
    __tablename__ = 'CS_CASES'
    id = Column(Integer, primary_key=True)
    skins = relationship("CS_SKINS", secondary = cs_skin_case, back_populates= "cs_cases")

It's throwing this error

sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship CS_SKINS.cs_cases - there are no foreign keys linking these tables via secondary table 'cs_skin_case'.  Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify 'primaryjoin' and 'secondaryjoin' expressions.```

when I try to append
```py
skin.cs_cases.append(case)
session.commit()

What I expected:

  • A association table called cs_skin_case, so I can join cs_skins and cs_cases using sqlalchemy
  • skin.cs_cases.append(case) creates a row on skins_cases mysql database, with case_id and skin_id

What I tried:

  • Make a separate class for cs_skin_case
  • Mess with relationship() parameters
  • to make sense of Flask version of SQLAlchemy but with no success

Solution

  • Your table name is CS_SKINS and CS_CASES so you have to use the same name in ForeignKey('CS_SKINS.id') and ForeignKey('CS_CASES.id').

    There is also another mistake in relationship("CS_CASES", secondary = cs_skin_case, back_populates= "cs_skins")

    It has to be relationship("CS_CASES", secondary = cs_skin_case, back_populates= "skins").