Getting sorted results in Flask-sqlalchemy

可紊 提交于 2019-12-12 03:36:44

问题


I have a MySQL database and below are the two Models defined.

class Agent(db.Model):
   id = db.Column(db.Integer, primary_key=True)
   email = db.Column(db.String(255), nullable=False, unique=True)
   premium_date = db.Column(db.DateTime, nullable=True)

class Property(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    agent_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    agent = db.relationship('Agent')
    title = db.Column(db.String(255), nullable=False)

I am getting all the properties using below query: properties = models.Property.query.all()

and Agents with premium_date using below query: agents = models.Agent.query.filter(models.Agent.premium_date is not None).all()

But I want to display the properties posted by the agents who has premium(agent.premium_date) first and then display rest of the properties. (It's like giving priority to premium agents).

note: since premium_date is optional, Some agents wont be premium users so the column will be empty.

Is there anyway to do this in Flask-SQLAlchemy? Any help would be great.


回答1:


You could use order_by(model.Agent.premium_date.desc()) to sort all agents with a premium date to the top, however this will also sort those agents with premium dates in descending order of those dates, which may not be optimal.

A better option, I think, would be to pull the two lists separately and then sort and append them in Python rather than relying on SQL to do it.



来源:https://stackoverflow.com/questions/35096259/getting-sorted-results-in-flask-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!