Timmy
Timmy

Reputation: 12828

SQLAlchemy Relationship Filter?

Can I do

table.relationship.filter( column = value )

to get a subset of rows for relationships? and the same for order_by?

Upvotes: 32

Views: 35437

Answers (2)

nosklo
nosklo

Reputation: 222852

According to the relationship() documentation, you can use order_by keyword argument with relationships, to set the order that will be returned. On the same page, it mentions that you can also use primaryjoin keyword argument to define extra join parameters. I think that can be used for the filter you want.

Example:

tasks = relationship(
    "Task",
    order_by="Task.priority",
    primaryjoin="and_(Task.list_id==List.id, Task.completed==None)",
    back_populates="task_list",
)

Upvotes: 18

Denis Otkidach
Denis Otkidach

Reputation: 33200

relationship() with lazy='dynamic' option gives you a query (AppenderQuery object which allows you to add/remove items), so you can .filter()/.filter_by() and .order_by() it.

Upvotes: 51

Related Questions