Python 将关系转换为查询对象
假设我在表用户和汽车之间有多对多关系 当我使用时,它工作得很好Python 将关系转换为查询对象,python,mysql,sqlalchemy,flask,flask-sqlalchemy,Python,Mysql,Sqlalchemy,Flask,Flask Sqlalchemy,假设我在表用户和汽车之间有多对多关系 当我使用时,它工作得很好 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 有什么方法可以做到这一点吗?老实说,我看不出您提供的代码示例实
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
有什么方法可以做到这一点吗?老实说,我看不出您提供的代码示例实际上是如何工作的,因为它返回一个列表。因此,
[]用户
应该生成一个错误
在任何情况下,以下都是一些选项:
# 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的更多信息:老实说,我看不出您提供的代码示例实际上是如何工作的,因为它返回一个列表。因此,
[]用户
应该生成一个错误
在任何情况下,以下都是一些选项:
# 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的更多信息,请参见此处: