python-3.xsqlitepyqt5qtableviewqsqlquerymodel

How to show last two rows only in tableview from sqlite using with QSqlQueryModel?


Below is my example code:

db = QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('book.db')
db.open()

model = QSqlQueryModel()
model.setQuery("SELECT * FROM card")
self.tableView.setModel(model)

I am using QSqlQueryModel, Qtablevie, Sqlite3, and able to view all rows in my table. But i want to view only last two rows of my table which are newly inserted rows in to the table. The table has no "id" field and it has numaric and text fields. How is it possible? Below is the table image: enter image description here


Solution

  • If you want to get the last 2 elements ordered by any field that indicates the insertion order, in your case "rowid", then you have to use a filter in the SQL command like this:

    model.setQuery("SELECT * FROM card ORDER BY rowid DESC LIMIT 2")
    

    Another possible option is to filter the table using QSortFilterProxyModel but it is more inefficient.