Search code examples
pythonflasksqlalchemyone-to-many

How to use order_by in one to many relationship in flask depending on a condition


I have two models question and answers in relationship , I can query a specific question and then print it's answers but I want to know how to order the answers by one of their column

I read many SO questions but they define it when creating the table, but I want to order the answers on condition, votes or date like here on stackoverflow,

class Question(db.Model):
    sno = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100))
    ans =  db.relationship("Answers",backref="owner")

class Answers(db.Model):
    ans_no = db.Column(db.Integer, primary_key=True)
    answer = db.Column(db.String(3000))
    votes = db.Column(db.Integer(),default=0)
    date = db.Column(db.String(15))
    ques_id =  db.Column(db.Integer,db.ForeignKey("question.sno"))

I want something like

q1 = Question.query.filter_by(sno=1).first()
q1.ans // gives me [<Answers1>,<Answers3>] so on 

How can I order the q1.ans on basis of votes or date. any suggestions would be really appreciated


Solution

  • If you always would like this to be the case, just add order_by=date to your relationship definition.

    Otherwise, just perform a separate query:

    sorted_anwers = Answer.query.where(with_parent(q1, Answer.owner)).order_by(Answer.votes.desc())