Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy Flask filter query to combine results from two models

I am trying to order a user's thanks(posts) by date_registered.

At the moment, there are two queries to get two lists, then manually combine and re-order. A user can be a giver of thank or a receiver. A thank has always a single giver, however might have multiple receivers. Therefore I have a Thank and a ThankReceivedByUser models to achive results.

class Thank(db.Model):

    id = db.Column(db.Integer, primary_key = True)
    giver_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable = False)
    status = db.Column(db.SmallInteger, nullable = False) 
    date_registered = db.Column(db.DateTime, nullable = False)

class ThankReceivedByUser(db.Model):

    id = db.Column(db.Integer, primary_key = True)
    thank_id = db.Column(db.Integer, db.ForeignKey("thank.id"), nullable = False)
    receiver_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable = False)
    status = db.Column(db.SmallInteger, nullable = False) 
    date_registered = db.Column(db.DateTime, nullable = False)

It would be great to get some hints on constructing a single query if possible.

like image 964
Dogukan Tufekci Avatar asked Dec 06 '22 09:12

Dogukan Tufekci


1 Answers

I came up with a solution to this problem:

thanks = Thank.query\
    .join(ThanksReceivedByUser)\
    .filter(or_(Thank.giver_id == user.id, 
                ThankReceivedByUser.receiver_id == user.id))\
    .order_by(Thank.date_registered).all()
like image 175
Dogukan Tufekci Avatar answered May 13 '23 14:05

Dogukan Tufekci