我具有以下架构:
class Account(db.Model):
id = Column(Integer, primary_key=True)
agency = Column(Integer, nullable=False)
account = Column(Integer, nullable=False, unique=True)
balance = Column(Float, nullable=False)
users = relationship('User', backref='account', lazy=True)
class User(db.Model):
id = Column(Integer, primary_key=True)
username = Column(String(40), nullable=False)
password = Column(String(40), nullable=False)
account_id = Column(Integer, ForeignKey('account.id'))
想象一下Richard和Jessica可以与他们的特定用户一起访问Account
数据。当我运行一个帐户查询以查找Richard的用户时,我想加载users
上的查询用户。像这样:
Account(id=1, agency=1478, number=124578, balance=117.5,
users=[User(id=1, username=Richard, password=1234)])
目前,我正在获取与该帐户相关的所有用户。示例:
Account(id=1, agency=1478, number=124578, balance=117.5,
users=[
User(id=1, username=Richard, password=1234),
User(id=2, username=Jessica, password=1234)
])
我要过滤它。我尝试过:
acc = Account.query.filter(User.username == 'Richard').one()
acc = Account.query.join(Account.users).filter(User.username == 'Richard').one()
acc = Account.query.filter(Account.users.any(User.username == 'Richard')).one()
但是我仍在吸引所有用户。 如何更改查询以获取预期的输出?