8

我正在使用带有以下模型的 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)

在 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

问题是,即使给函数指定了开始和结束日期,它也会返回按作者过滤的帖子,而不是按日期参数过滤的帖子。

正确的方法是什么?

编辑:生成的查询

SELECT post.id AS post_id, post.page_id AS post_page_id, post.author AS post_author ... FROM post WHERE post.author = ?
4

1 回答 1

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
于 2012-09-20T17:23:44.743 回答