pythonpyqtqtsqlqsqltablemodelqsqlquerymodel

Print QSqlModel's SQL code


Is there a way to print a QSqlTableModel/QueryModel's SQL code that is sent to the database? (I am working with filters and would like to use this for debugging purposes)

Something like:

self.model = QSqlTableModel()
self.model.setTable("Person")
print(self.model.sql)     #there is no command like .sql

Solution

  • If you want to get the SQL the first thing you should do is get the QSqlQuery, the QSqlTableModel / QueryModel classes have the query() method that returns that value, then to get the sql used in some query the lastQuery() method is used.

    In your case:

    print(self.model.query().lastQuery())