mecio
mecio

Reputation: 263

Convert relationship to query object

Let's say I have many to many relationship between tables User and Car.

It works fine when I use

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

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

I have created function that converts BaseQuery to xml object so I need to extract BaseQuery from Car.query.filter_by(vin='xxxxxx').all().users.

Is there any way to do that?

Upvotes: 0

Views: 366

Answers (1)

van
van

Reputation: 76962

Honestly, I do not see how the code samples you gave actually work, because Query.all() returns a list. so [].users should generate an error.

In any case, below are few options:

# 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)

See more info on option-3 here: orm.relationship(...)

Upvotes: 4

Related Questions