S
S
sergaso2021-10-17 17:46:53
Flask
sergaso, 2021-10-17 17:46:53

How to do a left outer join using flask-sqlalchemy?

There are three tables:

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    score = db.Column(db.Integer, nullable=False, default=0)
    results = db.relationship('Result', backref='solver', lazy='dynamic')

class Riddle(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    text = db.Column(db.String, unique=True, nullable=False)
    answer = db.Column(db.String, nullable=False)
    solutions = db.relationship('Result', backref='rebus', lazy='dynamic')
    points = db.Column(db.Integer, default=1)

class Result(db.Model):
    id = db.Column(db.Integer, primary_key=True) 
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    riddle_id = db.Column(db.Integer, db.ForeignKey('riddle.id'))


How can I get all the fields with riddles that the user does not have in their results (user.results)?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sergaso, 2021-10-25
@sergaso

The solution was found:

SELECT *
FROM riddle
EXCEPT
SELECT riddle.*
FROM riddle
JOIN result ON result.riddle_id = riddle.id
WHERE result.user_id = 1

riddle = Riddle.query.filter(Riddle.theme == theme_id) \
            .except_(Riddle.query.join(Result, Result.riddle_id == Riddle.id) \
            .filter(Result.user_id == user.id)).all()

K
Kadabrov, 2021-10-17
@Kadabrov

Great Flask Many-to-Many Tutorial

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question