【问题标题】:sqlalchemy conditional multiple filters on dynamic lazy relationshipsqlalchemy 对动态惰性关系的条件多个过滤器
【发布时间】:2012-09-20 17:04:34
【问题描述】:

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

【问题讨论】:

    标签: python sqlalchemy flask flask-sqlalchemy


    【解决方案1】:

    filter() 返回一个新的查询对象,但您不存储它。每次用结果替换p

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

    【讨论】:

      猜你喜欢
      • 2015-03-30
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 2012-01-23
      • 2016-09-17
      • 2014-03-12
      相关资源
      最近更新 更多