Sqlalchemy complex不在另一个表查询中

2024-04-19 17:20:43 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,我要道歉,因为我的SQL知识水平还很低。基本上问题是:我有两个不同的表,它们之间没有direct关系,但是它们共享两列:storm iu id和userid。在

基本上,我想查询所有来自storm iu 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'))

Banneduser

^{pr2}$

Post和Banneduser都是另一个table(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/.过滤器(~Post.userid.in_(bannedusers))\每次给出一个输出post.userid不在横幅广告中,所以我得到N个重复的帖子。我试图用distinct过滤这个,但它不起作用

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


Tags: theinid过滤器dbcolumnquerypost
1条回答
网友
1楼 · 发布于 2024-04-19 17:20:43

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

相关问题 更多 >