"SqlAlchemy与通过双重关系获取我的用户角色"

2024-10-02 12:24:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有三张桌子:

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)

Tags: keynameselfidbycolumnintegerprofile
1条回答
网友
1楼 · 发布于 2024-10-02 12:24:30

这是标准的多对多关系,在SQLAlchemy中很容易表达:http://docs.sqlalchemy.org/en/rel_0_8/orm/relationships.html#many-to-many

您需要将中间表指定为secondary参数的relationship。在最简单的情况下,不需要提供显式的primaryjoin,SQLAlchemy可以自己从元数据中找出连接条件。在

profile_roles = Table('profilerole', Base.metadata,
    Column('role_id', Integer, ForeignKey('role.id'), primary_key=True),
    Column('profile_id', Integer, ForeignKey('profile.id')), primary_key=True)


class Profile(Base):
    ...
    roles = relationship('Role', secondary=profile_roles, backref='profiles')

如果已经为中间表定义了声明性模型,那么可以将<modelclass>.__table__指定为secondary参数,而不是使用SQLAlchemy core。但也许您不需要这个表的完整模型:SQLAlchemy知道它需要用metadata.create_all创建它,并且关系可以通过collections接口进行操作。在

相关问题 更多 >

    热门问题