gpt4 book ai didi

python - 将关系转换为查询对象

转载 作者:太空宇宙 更新时间:2023-11-03 11:06:06 25 4
gpt4 key购买 nike

假设我在表 User 和 Car 之间有多对多关系。

我用的时候很好用

User.query.filter_by(name='somename').all().cars

Car.query.filter_by(vin='xxxxxx').all().users

我已经创建了将 BaseQuery 转换为 xml 对象的函数,因此我需要从 Car.query.filter_by(vin='xxxxxx').all().users 中提取 BaseQuery。

有什么办法吗?

最佳答案

老实说,我看不出你给出的代码示例是如何工作的,因为Query.all()返回一个列表。所以 [].users 应该会产生一个错误。

无论如何,以下是几个选项:

# 1: this should be fine
qry1 = Car.query.join(User, Car.users).filter(User.name=='you')

# 1: this will probably not work for you, as this is not one query, although the result is a Query instance
usr1 = User.query.filter_by(name='you').one()
qry2 = Car.query.with_parent(usr1)

# 3: you might define the relationship to be lazy='dynamic', in which case the query object instance will be returned
from sqlalchemy.orm.query import Query
class Car(Base):
__tablename__ = 'cars'
id = Column(Integer, primary_key=True)
vin = Column(String(50), unique=True, nullable=False)

users = relationship(User, secondary=user_cars,
#backref='cars',
backref=backref('cars', lazy="dynamic"),
lazy="dynamic",
)
qry3 = Car.query.filter_by(name="you").one().cars
assert isinstance(qry3, Query)

在此处查看有关选项 3 的更多信息:orm.relationship(...)

关于python - 将关系转换为查询对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11842174/

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