Hello, I meant something else. I assume that some Keywords were not assigned to any BlogPost. And now, without any modification to model, I would like to get a list of Keywords that are assigned to some BlogPosts. If it was one to many relation then I would just do:
list_of_used_keywords = session.query(BlogPost.keyword_id).distinct().all() But how to do that for many-to-many relation? Regards, Michal On Monday, December 19, 2016 at 6:19:22 PM UTC+1, Jonathan Vanasco wrote: > > > > On Monday, December 19, 2016 at 11:26:31 AM UTC-5, Michal Nowikowski wrote: >> >> Imagine that we have many Keywords but not all of them are used (not all >> are associated to some BlogPosts). >> Now, how to get list of Keywords that are used anywhere (i.e. these that >> are associated to some BlogPosts)? >> > > I'm not sure what you mean by this, so I'll try my best: > > Answer #1: query the Keyword class directly to find all the keywords. > > Answer #2: If you want to filter the keywords based on a keyword being > used in at least one or more posts (or None at all), it would be easiest to > use a PostKeywords ORM class to handle the database table (instead of the > lower-level core "Table" construct, as in the example). Then you join that > onto your query and filter against that. > > If you go a bit deeper into the ORM documentation on these chapters ( > http://docs.sqlalchemy.org/en/latest/orm/relationships.html) , it shows > association classes instead of tables and goes into a deep 'howto" for this > type of filtering. > > It looks like Mike was trying to build-up some working knowledge in the > chapter/example you cited. > -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To post to this group, send email to sqlalchemy@googlegroups.com. Visit this group at https://groups.google.com/group/sqlalchemy. For more options, visit https://groups.google.com/d/optout.