从SQLAlchemy关系中获取特定列

时间:2016-07-19 15:49:41

标签: python sqlalchemy

我需要允许用户阻止我的应用中的其他用户。当我想检查用户是否被当前(登录用户)阻止时,我的问题就出现了。如何检查特定用户是否在当前用户的阻止列表中?我的模型如下:

class User(db.Model):
__tablename__ = 'users'

id = Column(Integer, primary_key=True)
urid = Column(String(50), unique=True)
full_name = Column(String(100))
...

blockedlist = relationship('Blacklist', primaryjoin='Blacklist.user_id==User.id', back_populates='owner')

class Blacklist(db.Model):
__tablename__ = 'blacklist'

id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'))
blocked_id = Column(Integer, ForeignKey('users.id'))
date_blocked = Column(DateTime, default=func.now())

owner = relationship('User', primaryjoin='Blacklist.user_id==User.id', back_populates='blockedlist')
blocked = relationship('User', primaryjoin='Blacklist.blocked_id==User.id')

def __init__(self, user_id, blocked_id):
    self.user_id = user_id
    self.blocked_id = blocked_id

基本上,我想检查用户的ID是否在当前用户的被阻止ID列表中

1 个答案:

答案 0 :(得分:0)

您可以对关系使用.any,例如:

alice = User(urid='alice', full_name='Alice')
bob = User(urid='bob', full_name='Bob')

session.add(Blacklist(owner=alice, blocked=bob))
session.commit()

bob_blocked_alice = (
    session.query(User.blockedlist.any(blocked_id=alice.id))
    .filter(User.id == bob.id)
    .scalar()
)

print('Did Bob block Alice:', bob_blocked_alice)

alice_blocked_bob = (
    session.query(User.blockedlist.any(blocked_id=bob.id))
    .filter(User.id == alice.id)
    .scalar()
)

print('Did Alice block Bob:', alice_blocked_bob)

另外,您可以使用foreign_keys参数简化关系:

blockedlist = relationship('Blacklist', foreign_keys='Blacklist.user_id', back_populates='owner')

owner = relationship('User', foreign_keys=user_id, back_populates='blockedlist')
blocked = relationship('User', foreign_keys=blocked_id)