python - SQLAlchemy: Return list of associated records shared by two given records -


If / how can I return the list of tags shared between two blog posts with SQLAlchemy or if I need to draw each tag separately and compare it on the Python side. Take this example (borrowed from):

  import sqlalchemy alc session = alc.seessionmaker (bind = engine) session = session () base = alc.declarative_base (bind = engine) ) Class tag (base): __tablename__ = 'tags' id = alc.column (alc.Integer, primary_key = true) name = alc.Column (alc.String) def __repr __ (self): return' & lt; Tag '% s' & gt;' % Self.name class post (base): __tablename__ = 'posts' id = alc.column (alc.Integer, primary_key = true) text = alc.Column (alc.String) def __repr __ (self): return' & lt ; Post ID% d & gt; '% Self.id class postag (base): __tablename__ =' post_tags' post_id = alc.Column (alc.Integer, alc.ForeignKey ('posts.id'), primary_key = true) tag_ id = alc.Column (alc.Integer , Alc.ForeignKey ('tags.id'), primary_keys = True) = = alc.relationship ("post", backref = "ptags") tag = alc.relationship ("tag", backref = "tposts") tagging_user_name = alc. Column (Alec String)   

I am trying to figure out that to return a given query to two posts, returned a list of tags shared by both Will go. For example, if we have a tag "recipe", "audio", "sweet" and "vegetarian" with post_1 tag "recipe", "guestpost", "video", and "vegetarian", and post_2. .

I have come to know:

   session.query (post) .join (posttag) .filter (posttag tag.has (name = 'joke' )). All ()   

will return every post to "joke" in a list, but I am hurt that how do I get a list of tags shared between two posts, which I Want to start with tag ? Any help would be much appreciated.

This works for me:

  to sqlalchemy.sql Import is present, and_ pt1 = exists (). Where (and ((PostTag.tag_id == Tag.id, PostTag.post_id == id1)) pt2 = exists (where) (and_ (PostTag.tag_id == Tag.id, PostTag post_id == id2)) tags = Session.query (Tag.name) .filter (pt1, pt2) .all ()   

The SQL should produce as follows:

  The name of the tag is present from selection (post_ tags from selection 1 where tag_ id = id and post_ id = & lt; post id 1 & gt;) and existing (SELECT 1 FROM post_tags WHERE tag_ id = id and post_id = & lt; post id 2 & gt ;)    

Comments

Popular posts from this blog

Verilog Error: output or inout port "Q" must be connected to a structural net expression -

jasper reports - How to center align barcode using jasperreports and barcode4j -

c# - ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value -