Python Sqlalchemy complex不在另一个表查询中

Python Sqlalchemy complex不在另一个表查询中,python,sqlalchemy,Python,Sqlalchemy,首先,我想道歉,因为我的SQL知识水平仍然很低。基本上问题如下:我有两个不同的表,它们之间没有直接关系,但它们共享两列:storm_id和userid 基本上,我想从storm_id查询所有帖子,这些帖子不是来自被禁止的用户和一些额外的过滤器 以下是模型: 邮递 班纳杜塞 Post和Banneduser都是另一个table(Storm)儿童。这是我试图输出的查询。如您所见,我正在尝试筛选: 核定员额 按降序排列 有一个限制(我把它与查询分开,因为elif有其他过滤器) 我有两个问题,一个是

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

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

以下是模型:

邮递 班纳杜塞 Post和Banneduser都是另一个table(Storm)儿童。这是我试图输出的查询。如您所见,我正在尝试筛选:

  • 核定员额
  • 按降序排列
  • 有一个限制(我把它与查询分开,因为elif有其他过滤器)

我有两个问题,一个是基本问题,一个是根本问题:

1/.filter(~Post.userid.in_(bannedusers))\每次Post.userid不在bannedusers中时都会给出一个输出,因此我得到N个重复的帖子。我尝试用distinct过滤这个,但它不起作用

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

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

db.session.query(Post)\
.filter(Post.storm_id==storm id)\
.filter(Post.verified==True)\
.filter(~exists()。其中(banendduser.storm\u id==Post.storm\u id))\
.order_by(Post.timenow.desc())

Hey@jmrueda,你能接受下面的答案吗?这正好解决了你的问题。
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'))
# 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