jmrueda
jmrueda

Reputation: 1418

Sqlalchemy complex NOT IN another table query

First of all, i would like to apologize as my SQL knowledge level is still very low. Basically the problem is the following: I have two distinct tables, no direct relationship between them, but they share two columns: storm_id and userid.

Basically, i would like to query all posts from storm_id, that are not from a banned user and some extra filters.

Here are the models:

Post

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

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'))

Both Post and Banneduser are another table (Storm) children. And here is the query i am trying to output. As you can see, i am trying to filter:

I got two problems, one basic and one underlying problem:

1/ .filter(~Post.userid.in_(bannedusers))\ gives one output EACH TIME post.userid is not in bannedusers, so i get N repeated posts. I try to filter this with distinct, but it does not work

2/ Underlying problem: i am not sure if my approach is the correct one (the ddbb model structure/relationship plus the queries)

Upvotes: 11

Views: 6478

Answers (1)

Bartek Jablonski
Bartek Jablonski

Reputation: 2727

Use SQL EXISTS. Your query should be like this:

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

Upvotes: 22

Related Questions