Sqlalchemy Filter Children In Query, But Not Parent
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 the posts found in User.post based on a spec
Solution 1:
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))
Solution 2:
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()
Baca Juga
- Python, Sqlalchemy Pass Parameters In Connection.execute
- How To Sync A Mysql Databases Between Two Remote Databases (without Mysql Database Replication Technique )
- How Can I Query And Get Data From My Sqlite Database Even When My Search Input Have Similar Words That Is Apart From Each Other (not Continuously)
Post a Comment for "Sqlalchemy Filter Children In Query, But Not Parent"