繁体   English   中英

SQLAlchemy复杂不在另一个表查询

[英]Sqlalchemy complex NOT IN another table query

首先,我很抱歉,因为我的SQL知识水平仍然很低。 基本上,问题如下:我有两个不同的表,它们之间没有直接关系,但是它们共享两列:storm_id和userid。

基本上,我想查询来自storm_id的所有帖子,这些帖子不是来自被禁止的用户和一些额外的过滤器。

这些是模型:

发布

class Post(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    ...
    userid = db.Column(db.String(100))
    ...
    storm_id = db.Column(db.Integer, db.ForeignKey('storm.id'))

被禁用户

class Banneduser(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    sn = db.Column(db.String(60))
    userid = db.Column(db.String(100))
    name = db.Column(db.String(60))
    storm_id = db.Column(db.Integer, db.ForeignKey('storm.id'))

Post和Banneduser都是另一个表(风暴)子级。 这是我要输出的查询。 如您所见,我正在尝试过滤:

  • 验证过的帖子
  • 按降序排列
  • 有限制(我把它与查询分开,因为elif还有其他过滤器)

     # we query banned users id bannedusers = db.session.query(Banneduser.userid) # we do the query except the limit, as in the if..elif there are more filtering queries joined = db.session.query(Post, Banneduser)\\ .filter(Post.storm_id==stormid)\\ .filter(Post.verified==True)\\ # here comes the trouble .filter(~Post.userid.in_(bannedusers))\\ .order_by(Post.timenow.desc())\\ try: if contentsettings.filterby == 'all': posts = joined.limit(contentsettings.maxposts) print((posts.all())) # i am not sure if this is pythonic posts = [item[0] for item in posts] return render_template("stream.html", storm=storm, wall=posts) elif ... other queries 

我遇到两个问题,一个是基本问题,另一个是基本问题:

1 / .filter(〜Post.userid.in_(bannedusers))\\给出一个输出EACH TIME post.userid不在bannedusers中,所以我得到了N个重复的帖子。 我尝试用与众不同的方式对此进行过滤,但它不起作用

2 /基本问题:我不确定我的方法是否正确(ddbb模型结构/关系以及查询)

使用SQL EXISTS 您的查询应如下所示:

db.session.query(Post)\
  .filter(Post.storm_id==stormid)\
  .filter(Post.verified==True)\
  .filter(~ exists().where(Banneduser.storm_id==Post.storm_id))\
  .order_by(Post.timenow.desc())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM