使用SQLAlchemy按属性或相关属性查询

时间:2018-11-09 18:15:09

标签: python sqlalchemy

我的抽象是: Book 只有一个 User (作为 author ),并且与 User < / em>(作为合作者):

class UserBook(Base):
    __tablename__ = 'user_book'
    user_id = Column(String(512), ForeignKey('user.id'), primary_key=True)
    book_id = Column(String(512), ForeignKey('book.id'), primary_key=True)
    collaboration_type = Column(Integer, default=1)
    book = relationship('Book', back_populates='users')
    user = relationship('User', back_populates='books')


class User(Base):
    __tablename__ = 'user'

    id = Column(String(512), primary_key=True)
    books = relationship('UserBook', back_populates='user')


class Book(Base):
    __tablename__ = 'book'

    id = Column(String(512), primary_key=True)
    author = Column(String(512), ForeignKey('user.id'), nullable=False)
    collaborators = relationship('UserBook', back_populates='book')
    name = Column(String(512))
    description = Column(String(512), default='')

我希望选择所有作者为的图书,如果可能的话,我将使用SQLAlchemy声明性查询。

我能够与协作者进行加入,但是我不确定如何使用作者过滤器。

1 个答案:

答案 0 :(得分:2)

您可以在过滤器上使用or_运算符,以获取当前用户是作者或协作者的所有书籍。例如:

from sqlalchemy import or_


curr_id = 'current_user_id'

session.query(Book).\
    outerjoin(UserBook).\
    filter(or_(Book.author == curr_id, UserBook.user_id == curr_id)).\
    all()