我有三个表,定义为:
class User(Base):
__tablename__ = 'users'
id = Column(Integer(10), primary_key=True)
firstname = Column(String(64))
surname = Column(String(64))
class SWMS(Base):
__tablename__ = 'swms'
id = Column(Integer(10), primary_key=True)
owner_id = Column(Integer(10), ForeignKey('users.id', ondelete='CASCADE'))
filename = Column(String(255))
swmowner = relationship('User', backref=backref('users'))
class SWM_perms(Base):
__tablename__ = 'swm_perms'
id = Column(Integer(10), primary_key=True)
swm_id = Column(Integer(10), ForeignKey('swms.id', ondelete='CASCADE'))
user_id = Column(Integer(10), ForeignKey('users.id', ondelete='CASCADE'))
swm = relationship('SWMS', backref=backref('swms'))
swmuser = relationship('User', backref=backref('swmusers'))
本质上,SWMS 表是一个文档信息表,其中 owner_id 定义了创建文档的用户。SWM_perms 是一个表,其中包含文档 ID 到用户 ID 的映射 - 用于定义允许哪些用户查看文档。
要生成所有文档的表,这些文档要么 1)由用户拥有,要么 2)可由用户查看,在 SQL 中我会这样做:
select owner_id, users.firstname, users.surname, filename
from swms, swm_perms, users
where users.id=swms.owner_id and
((swms.id=swm_perms.swm_id and swm_perms.user_id = 27) or (owner_id = 27));
您将如何在 sqlalchemy 中定义此查询?我熟悉 or_() 函数,但我尝试的变体不会生成正确的对象。