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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With