sqlalchemy条件多动态懒惰关系的过滤器 [英] sqlalchemy conditional multiple filters on dynamic lazy relationship

查看:273
本文介绍了sqlalchemy条件多动态懒惰关系的过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用sqlalchemy和以下模型:
$ b $ pre $ class $ page $(db.Model)
id = 。
posts = db.relationship('Post',lazy ='dynamic')
$ b $ class Post(db.Model):
id = ..
page_id = ..
author = db.Column(db.String)
date = db.Column(db.DateTime)

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



<$ p $
$ self_posts.filter(Post.author == author)

if start_date(author_post_posts(author,start_date = None,end_date = None) :
p.filter(Post.date> =开始日期)

如果结束日期:
p.filter(Post.date< = end_date)

返回p

问题是,即使给函数的开始和结束日期,返回由作者过滤后,但从来没有由日期参数。



正确的做法是什么?

编辑:生成的查询

  SELECT post.id AS post_id,post.page_id AS post_page_id,post.author AS post_author ... FROM post WHERE post。作者=? 


解决方案

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

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

如果end_date:
p = p.filter(Post.date< = end_date)

返回p


I am using sqlalchemy with the following models

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)

in the Page class I have a method to get the page's posts for a specific date and author, it looks like that

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

The problem is, even if the function is given a start and end date, it returns post filtered by author but never by the dates argument.

What's the right way to do it?

Edit: The query generated

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

解决方案

filter() returns a new query object, but you do not store it. Replace p with the result each time:

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

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

return p

这篇关于sqlalchemy条件多动态懒惰关系的过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆