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:
cs_skin_case
, so I can join cs_skins and cs_cases using sqlalchemyskin.cs_cases.append(case)
creates a row on skins_cases mysql database, with case_id and skin_idWhat I tried:
cs_skin_case
relationship()
parametersYour 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")
.