我正在尝试使用models.py和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")
字符串
它抛出了这个错误
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()
型
我期待的是:
- 一个名为
cs_skin_case
的关联表,因此我可以使用sqlalchemistry连接cs_skins和cs_cases skin.cs_cases.append(case)
在skins_cases MySQL数据库中创建一行,其中包含case_id和skin_id
我尝试的是:
- 为
cs_skin_case
创建单独的类 relationship()
参数混乱- 理解Flask版本的SQLAlchemy,但没有成功
1条答案
按热度按时间bis0qfac1#
您的表名是
CS_SKINS
和CS_CASES
,因此您必须在ForeignKey('CS_SKINS.id')
和ForeignKey('CS_CASES.id')
中使用相同的名称。relationship("CS_CASES", secondary = cs_skin_case, back_populates= "cs_skins")
中还有一个错误必须是
relationship("CS_CASES", secondary = cs_skin_case, back_populates= "skins")
。