1

I have created User table:

class User(db.Model):

    id = db.Column(db.String(4), primary_key=True)
    username = db.Column(db.String(100))

    def __repr__(self):
        return f'<User {self.id}>'

When I add two users like this:

u2 = User(id='u002', username='User2')
u1 = User(id='u001', username='User1')
db.session.add_all([u2, u1])
db.session.commit()

I want to have my table always sorted by User.id, despite the order I am adding new users. Is it possible to do this? I have only found a way to order relationship.

marcin
  • 517
  • 4
  • 23

1 Answers1

2

Internally, some databases sort their indexes (like those for Primary Key) but that just maintains a reference to the actual record. However, there's no way to sort data in a table - unless you want to export all data, delete records and then re-create the table with the records in the right order.

What you probably want instead is for your Views to show the table data sorted. And that's where you should do it. See these answers for reference:

aneroid
  • 12,983
  • 3
  • 36
  • 66