【问题标题】:Sqlalchemy complex NOT IN another table querySqlalchemy 复杂不在另一个表查询中
【发布时间】:2019-10-23 08:17:54
【问题描述】:

首先,我要道歉,因为我的 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 都是另一个表 (Storm) 子表。这是我要输出的查询。如您所见,我正在尝试过滤:

  • 已验证帖子
  • 按降序排列
  • 有一个限制(我把它与查询分开,因为 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))\ 每次都给出一个输出 post.userid 不在被禁止的用户中,所以我得到 N 个重复的帖子。我尝试用 distinct 过滤它,但它不起作用

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

【问题讨论】:

  • 嘿@jmrueda,你能接受下面的答案吗?它完全解决了您的问题。

标签: python sqlalchemy


【解决方案1】:

使用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())

【讨论】:

    猜你喜欢
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 2014-05-01
    相关资源
    最近更新 更多