sqlalchemy filter children in query, but not parent

前端 未结 2 1915
慢半拍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))
    

提交回复
热议问题