我有三张桌子:
profile
id, int, pk
name...
role
id, int, pk
name
...
profilerole
role_id int, pk, foreign_key to role.id
profile_id int, pk, foreign_key to role.id
我想写一些东西来加载角色信息,目前我有以下配置文件类:
^{pr2}$上面这一行将给我来自表roleprofile
的角色信息,但是我希望它能提供role
表中的角色。在
这可能吗?我该怎么做?在
更新
使用此关系:
roles = relationship('role', secondary=roleprofile, backref='profiles')
为什么要定义这一点:
roleprofiles = Table('roleprofile', Base.metadata,
Column('role_id', Integer, ForeignKey('role.id')),
Column('profile_id', Integer, ForeignKey('profile.id'))
)
如果没有:
class roleprofile(Base):
__tablename__ = 'roleprofile'
role_id = Column(Integer, ForeignKey('role.id'), primary_key=True)
profile_id = Column(Integer, ForeignKey('profile.id'), primary_key=True)
def __init__(self, name, created_by, last_updated_by, created=datetime.now(), last_updated=datetime.now()):
self.name = name
self.created = created
self.created_by = created_by
self.last_updated = last_updated
self.last_updated_by = last_updated_by
当使用roleprofile
定义关联时,当已经定义时,我得到一个错误,因此它们看起来是相同的,但只有第一个有效。课堂上给我的错误是:
TypeError: __init__() takes at least 4 arguments (1 given)
这是标准的多对多关系,在SQLAlchemy中很容易表达:http://docs.sqlalchemy.org/en/rel_0_8/orm/relationships.html#many-to-many
您需要将中间表指定为
secondary
参数的relationship
。在最简单的情况下,不需要提供显式的primaryjoin
,SQLAlchemy可以自己从元数据中找出连接条件。在如果已经为中间表定义了声明性模型,那么可以将
<modelclass>.__table__
指定为secondary
参数,而不是使用SQLAlchemy core。但也许您不需要这个表的完整模型:SQLAlchemy知道它需要用metadata.create_all
创建它,并且关系可以通过collections接口进行操作。在相关问题 更多 >
编程相关推荐