开发者

sql alchemy filter results on properties of joined models

开发者 https://www.devze.com 2023-04-11 14:03 出处:网络
I have a model X and a model Y. Y contains a foreign key reference to X.id, with a instance of the related X entry available by the property x.

I have a model X and a model Y.

Y contains a foreign key reference to X.id, with a instance of the related X entry available by the property x.

x_id = Column(Integer, ForeignKey('xtable.id'))    
x = relationship('X')

X also has a boolean property 'publish'.

Executing a query on Y, how can i filter my results to those where x.publish is True;

Ive tried doing something like this:

DBSession.query(Y).filter_by(x.publish = True).all() 

But this doesnt work, i get an error saying keyword cant be an expression. Ive looked through the sql alchemy docs for a solution, but i 开发者_Python百科cant seem to find what im looking for. Any suggestions?


You need to add a join in your query to class X and use filter instead of filter_by:

qry = DBSession.query(Y)
qry = qry.join(X)
qry = qry.filter(X.publish == True)
qry.all()

or in one go:

DBSession.query(Y).join(X).filter(X.publish == True).all()

See this question regarding the difference between using filter and filter_by.


Other option is

You can create direct new relationship

Like

x1 = relationship(X,
             primaryjoin='and_(X.id==Y.x_id, X.publish==True)'
             )

This will do join automatically.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号