Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
558 views
in Technique[技术] by (71.8m points)

python - SQLAlchemy how to filter by children in many to many

I was asking for a problem I had in SQLAlchemy and found the solution while writing. I post it anyway just in case it helps somebody :)

Let's say I have a many to many relationship that seems to work (at least I can fetch children) Three tables: posts, tags and post_tags.

import sqlalchemy as alc

class Tag(Base):
    __tablename__ = 'tags'

    id = alc.Column(alc.Integer, primary_key=True)
    name = alc.Column(alc.String)
    accepted = alc.Column(alc.Integer)

    posts = relationship('Post', secondary=post_tags)



class Post(Base):

    __tablename__ = 'posts'

    id = alc.Column(alc.Integer, primary_key=True)
    text = alc.Column(alc.String)
    date_out = alc.Column(alc.Date)

    tags = relationship('Mistake_Code', secondary=post_tags)

# relational table
post_tags = alc.Table('check_point_mistakes',
                       Base.metadata,
                       alc.Column('post_id', alc.Integer,ForeignKey('posts.id')),
                       alc.Column('tag_id', alc.Integer, alc.ForeignKey('tags.id')))

Now my problem is that I want to filter first by date_out in Post. I can get it like this:

# assume start_date and end_date

query = (
            session.query(Post)
                   .filter(Post.date_out.between(start_date, end_date))
 )

But how to filter by tags at the same time?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
query = (
    session.query(Post)
           .join(Post.tags)     # It's necessary to join the "children" of Post
           .filter(Post.date_out.between(start_date, end_date))
           # here comes the magic: 
           # you can filter with Tag, even though it was not directly joined)
           .filter(Tag.accepted == 1)
)

Disclaimer: this is a veeery reduced example of my actual code, I might have made a mistake while simplifying.

I hope it helps somebody.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...