gpt4 book ai didi

python - 过滤 SQLAlchemy 关系

转载 作者:行者123 更新时间:2023-12-04 03:44:31 25 4
gpt4 key购买 nike

我正在使用 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'

最佳答案

您可以使用 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()

只需阅读引用文档即可获得有关这些主题的完整说明。

关于python - 过滤 SQLAlchemy 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15218732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com