我为以下组提供了简化的代码,这些组可以具有具有角色的子组:
Arc<GigabyteMap>
运行此命令时,我得到from sqlalchemy import (
CheckConstraint,
Column,
ForeignKey,
PrimaryKeyConstraint,
String,
create_engine,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
Base = declarative_base()
class Group(Base):
__tablename__ = 'groups'
name = Column(String, primary_key=True)
group_roles = relationship('GroupRole', back_populates='group')
class GroupRole(Base):
__tablename__ = 'group_roles'
name = Column(String, ForeignKey(Group.name))
group_name = Column(String, ForeignKey(Group.name))
role = Column(String, nullable=False)
__table_args__ = (
CheckConstraint('name != group_name'),
PrimaryKeyConstraint('name', 'group_name'),
)
group = relationship(Group,
foreign_keys=[name],
back_populates='group_roles')
engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)
session = sessionmaker(bind=engine)()
session.add(Group(name='test'))
我还尝试过在sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship Group.group_roles - there are multiple foreign key path
s 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.
表下方添加以下内容,以代替GroupRole
中已经定义的相应行:
Group
但是我遇到了同样的错误,而且看起来其他人也没有这样做。我究竟做错了什么?如何获得Group.group_roles = relationship('GroupRole', foreign_keys=[Column(String, ForeignKey(GroupRole.name))], back_populates='group')
表来引用我的GroupRole
表?我正在使用SQLAlchemy 1.3和python 3.7。
答案 0 :(得分:0)
您可以使代码仅与backref
关系上的GroupRole.group
一起使用,例如:
class Group(Base):
__tablename__ = 'groups'
name = Column(String, primary_key=True)
class GroupRole(Base):
__tablename__ = 'group_roles'
name = Column(String, ForeignKey(Group.name))
group_name = Column(String, ForeignKey(Group.name))
role = Column(String, nullable=False)
__table_args__ = (
CheckConstraint('name != group_name'),
PrimaryKeyConstraint('name', 'group_name'),
)
group = relationship(Group,
foreign_keys=[name],
backref='group_roles')
虽然不确定这是什么目的,但是可以工作:
g = Group(name='test', group_roles=[
GroupRole(group_name='testrole', name='test', role='testrole'),
GroupRole(group_name='testrole2', name='test', role='testrole2')
])
session.add(g)