我正在使用Pyramid + SQLAlchemy并进行以下设置
from sqlalchemy import orm
from __init__ import user_table
from device import Device
class User(object):
def __repr__(self):
return 'User: ' + self.username
orm.mapper(User, user_table, properties={
'devices': orm.relation(Device, backref='owner')
})
访问user.devices
时如何添加过滤器?当我尝试user.devices.filter(Device.platform==1).all()
时,我收到以下错误:
'InstrumentedList' object has no attribute 'filter'
答案 0 :(得分:2)
您可以使用Query-Enabled Property:
class User(object):
def __repr__(self):
return 'User: ' + self.username
# property
@property
def devices_filtered(self):
return object_session(self).query(Device).with_parent(self).filter(Device.platform==1).all()
# or simply a method
def devices_filtered(self, platform):
return object_session(self).query(Device).with_parent(self).filter(Device.platform==platform).all()
或查看Dynamic Relationship Loaders:
orm.mapper(User, user_table, properties={
'devices': orm.relation(Device, backref='owner', lazy='dynamic')
})
# ...
user = session.query(User).get(_some_user_id)
devices = user.devices.filter(Device.platform==platform).all()
请阅读参考文档,了解有关主题的完整说明。