J
J
Jekson2018-06-01 10:05:15
Flask
Jekson, 2018-06-01 10:05:15

Flask: how to sort list by model fields?

I have a simple model and a function to display model instances in an html template. The list is displayed.
models.py

class Datacener(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    number = db.Column(db.Integer)
    name = db.Column(db.String(64), index=True, unique=True)
    place = db.Column(db.String(64))
    capacity = db.Column(db.Integer, index=True)
    server = db.relationship('Server', backref='datacener', lazy=True)
    tier = db.Column(db.Integer)
    
    def __repr__(self):
        return '<Datacenter {}>'.format(self.name)

views.py
@app.route('/')
def index():
    datacenter = Datacener.query.all()   
    return render_template('index.html', title='Home', datacenter=datacenter)

I can't figure out how to sort by some model fields on this page. How to immediately display a sorted list, for example, according to the capacity field is clear:
datacenter = Datacener.query.order_by(Datacener.capacity)

And so that the user could sort?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question