sqlalchemy, select using reverse-inclusive (not in) list of child column values

前端 未结 4 1630
忘了有多久
忘了有多久 2021-02-02 10:30

I have a typical Post / Tags (many tags associated with one post) relationship in flask-sqlalchemy, and I want to select posts which aren\'t tagged with any tag in a list I prov

相关标签:
4条回答
  • 2021-02-02 10:58

    I thought up a nasty solution, but it works for the time being. I'd be interested to hear if anyone comes up with a smarter method.

    ignore_ids = [item.post_id for item in Tag.query.filter(Tag.name.in_(['dont','want','these'])).all()]
    Post.query.filter(Post.id.notin_(ignore_ids))
    
    0 讨论(0)
  • 2021-02-02 11:01

    The notin_ works for me, adjusted example:

    db.session.query(Post).filter(Post.tags.notin_(['dont','want','these'])) 
    
    0 讨论(0)
  • 2021-02-02 11:17

    Pretty straightforward using negated any:

    query = session.query(Post).filter(~Post.tags.any(Tag.name.in_(['dont', 'want', 'these'])))
    
    0 讨论(0)
  • Try this one, easy:

    users = session.query(Post).filter(not_(Post.tags.name.in_(['dont', 'want', these'])))
    

    Hope this helps!

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