我在询问我在 SQLAlchemy 中遇到的问题,并在写作时找到了解决方案。无论如何我都会发布它以防万一它对某人有帮助:)
假设我有一个似乎有效的多对多关系(至少我可以获取孩子) 三个表:posts、tags 和 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')))
现在我的问题是我想先在 Post 中按 date_out 过滤。我可以这样得到:
# assume start_date and end_date
query = (
session.query(Post)
.filter(Post.date_out.between(start_date, end_date))
)
但是如何同时按标签过滤呢?