SQLAlchemy将case语句映射到模型字段

2024-06-02 13:04:46 发布

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

我正在尝试映射在使用case语句执行查询后得到的两个布尔值。 我的模型如下:

class Account(Base, SerializableMixin):
    __tablename__ = 'accounts'

    id = Column(Integer, primary_key=True)

    followers = relationship(
        'Account', secondary='followers_followees',
         primaryjoin=(FollowAssociation.followee_id == id),
         secondaryjoin=(FollowAssociation.follower_id == id),
         backref='followees')

class FollowAssociation(Base):
    __tablename__ = 'followers_followees'

    follower_id = Column(Integer, ForeignKey('accounts.id'), primary_key=True)
    followee_id = Column(Integer, ForeignKey('accounts.id'), primary_key=True)
    created_at = Column(DateTime, default=datetime.datetime.now)

我的问题是:

with session_scope() as s:
    ali = aliased(FollowAssociation)
    s.query(Account, case([ (FollowAssociation.follower_id == None, False) ], else_=True),
        case([ (ali.follower_id == None, False) ], else_=True))\
     .outerjoin(FollowAssociation, and_(Account.id == FollowAssociation.followee_id, FollowAssociation.follower_id == 1))\
     .outerjoin(ali, and_(Account.id == ali.follower_id, ali.followee_id == 1)).all()

我得到的结果是: (<rsh.accounts.models.Account object at 0x7fe350477990>, False, False)

在我的模型中,有没有办法映射这两个布尔值,它们表示一个帐户后面是否跟有另一个帐户?谢谢


Tags: keyidfalsetruecolumnaccountintegerali
1条回答
网友
1楼 · 发布于 2024-06-02 13:04:46

这在炼金术中并不常见,但有可能。有几种方法可以做到这一点。 其中之一是构造自定义映射器实例。你知道吗

query = session.query(
    Account,
    case([(FollowAssociation.follower_id == None, False)], else_=True).label('first'),
    case([(ali.follower_id == None, False)], else_=True).label('second')
).outerjoin(
    FollowAssociation,
    and_(Account.id == FollowAssociation.followee_id, FollowAssociation.follower_id == 1)
).outerjoin(ali, and_(Account.id == ali.follower_id, ali.followee_id == 1))


class CustomAccount(object):
    pass


mapper(CustomAccount, query.statement.alias())

res = session.query(CustomAccount).all()
print(res[0].id)
print(res[0].first)

Here完整示例。 另一种可能的方法是使用hybrid_property。你知道吗

相关问题 更多 >