Pradeepb
Pradeepb

Reputation: 2562

Getting sorted results in Flask-sqlalchemy

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.

Upvotes: 3

Views: 5304

Answers (1)

Zaphodb2002
Zaphodb2002

Reputation: 206

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.

Upvotes: 8

Related Questions