sqlalchemy filter children in query, but not parent

前端 未结 2 1913
慢半拍i
慢半拍i 2021-01-21 02:16

I have a query which returns a User object. Users have a number of Posts which they have made. When I perform a query, I want to filter th

相关标签:
2条回答
  • 2021-01-21 02:31

    Loading custom filtered collections is done using contains_eager(). Since the goal is to load all User objects even if they have no Post objects that match the filtering criteria, an outerjoin() should be used and the predicates for posts put in the ON clause of the join:

    end = datetime(2019, 4, 10, 12, 0)
    start = end - timedelta(days=1)
    
    # If you want to use half closed intervals, replace `between` with
    # suitable relational comparisons.
    User.query.\
        outerjoin(Post, and_(Post.user_id == User.uid,
                             Post.time.between(start, end))).\
        options(contains_eager(User.post))
    
    0 讨论(0)
  • 2021-01-21 02:37

    I'm not sure this is what you are looking for, but what's wrong with this KISS approach?

    Post.query.filter(Post.user == <username>).filter(
        Post.time > START_OF_DAY).filter(Post.time < END_OF_DAY).all()
    
    0 讨论(0)
提交回复
热议问题