sqlalchemy条件多重过滤动态懒惰关系

app*_*ief 7 python sqlalchemy flask flask-sqlalchemy

我正在使用sqlalchemy以下型号

class Page(db.Model):
     id= ..
     posts = db.relationship('Post', lazy='dynamic')

class Post(db.Model):
   id=..
   page_id=..
   author= db.Column(db.String)
   date= db.Column(db.DateTime)
Run Code Online (Sandbox Code Playgroud)

在Page类我有一个方法来获取特定日期和作者的页面的帖子,它看起来像那样

def author_posts(author, start_date=None, end_date=None):
    p= self.posts.filter(Post.author == author)

    if start_date:
       p.filter(Post.date >= start_date)

    if end_date:
       p.filter(Post.date <= end_date)

    return p
Run Code Online (Sandbox Code Playgroud)

问题是,即使函数被赋予开始和结束日期,它也会返回由作者过滤的帖子,但不会返回日期参数.

什么是正确的方法呢?

编辑:生成的查询

SELECT post.id AS post_id, post.page_id AS post_page_id, post.author AS post_author ... FROM post WHERE post.author = ?
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 11

filter()返回一个新的查询对象,但不存储它.p每次都替换为结果:

if start_date:
   p = p.filter(Post.date >= start_date)

if end_date:
   p = p.filter(Post.date <= end_date)

return p
Run Code Online (Sandbox Code Playgroud)