Skip to content

Where clause on m2m field #266

Answered by sinisaos
serg-yalosovetsky asked this question in Q&A
Discussion options

You must be logged in to vote

On my example data user liked genres is Rock and Metal. Rock songs ids is 1,3,4,5,8,9 and Metal songs ids is 11,12. Result of your raw sql query for my example data is

[{'id': 1}, {'id': 3}, {'id': 4}, {'id': 5}, {'id': 8}, {'id': 9}, {'id': 11}, {'id': 12}]

The same can be achieved with these two queries.

from piccolo.utils.list import flatten

# user liked genres
liked_genres = await User.select(User.liked_genres(Genre.id, as_list=True)).where(
    User.id == 1
)
# flatten the result list for use in the next query
user_liked_genres = flatten([i["liked_genres"] for i in liked_genres])
# all songs for the genres that the user likes
all_genre_songs_user_like = await Genre.select(
    Genre.n…

Replies: 1 comment 4 replies

Comment options

You must be logged in to vote
4 replies
@serg-yalosovetsky
Comment options

@sinisaos
Comment options

@serg-yalosovetsky
Comment options

@sinisaos
Comment options

Answer selected by serg-yalosovetsky
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants