I have a query which returns a User
object. User
s have a number of Post
s which they have made. When I perform a query, I want to filter th
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))
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()