How to add an automatic filter to a relation with SQLAlchemy?

后端 未结 3 694
不思量自难忘°
不思量自难忘° 2021-02-08 09:54

I\'m using SQLAlchemy 0.5rc, and I\'d like to add an automatic filter to a relation, so that every time it tries to fetch records for that relation, it ignores the \"remote\" on

相关标签:
3条回答
  • 2021-02-08 10:40

    I'm only currently developing agains 0.4.something, but here's how I'd suggest it:

    db.query(Object).filter(Object.first==value).filter(Object.second==False).all()
    

    I think that's what you are trying to do, right?

    (Note: written in a web browser, not real code!)

    0 讨论(0)
  • 2021-02-08 10:47

    The and_() function is the correct way to do logical conjunctions in SQLAlchemy, together with the & operator, but be careful with the latter as it has surprising precedence rules, i.e. higher precedence than comparison operators.

    You could also use a string as a primary join with the text() constructor, but that will make your code break with any table aliasing that comes with eagerloading and joins.

    For logical deletion, it might be better to map the whole class over a select that ignores deleted values:

    mapper(Something, select([sometable], sometable.c.deleted == False))
    
    0 讨论(0)
  • 2021-02-08 10:54

    but is there a way to use a string as primaryjoin instead?

    You can use the following:

    children = relationship("Children", primaryjoin="and_(Parent.id==Children.parent_id, Children.logically_deleted==False)"
    

    This worked for me!

    0 讨论(0)
提交回复
热议问题