[PyQt] QRelationalTableModel usage question
Ricardo Araoz
ricaraoz at gmail.com
Wed Apr 11 01:15:54 BST 2018
Hi,
I'm looking at an app from a tutorial which instantiates a Main
window with two QTableViews in a master-detail relationship. You can see
the code for adding a master record below, when you add a master record
you MUST (requirement) add an initial detail record. This code will not
work properly.
The code starts a transaction, then adds an empty master record, then
queries the MAX() id from the master table and increments it by one,
simulating the PRIMARY KEY AUTOINCREMENT action of the database in the
id field, it then inserts a detail record and sets a relation with the
master table through the masterid field.
The code will work except when adding a master record after you've
deleted a master record, in which case the MAX(id) + 1 will not be the
next id (as the original maximum id has been deleted), and from then on
the initial detail records created will not be linked to the proper
master id.
I've tried to find out the proper id value by checking the
masterModel.data() value for the id, but it returns a QPyNullVariant,
tried a masterModel.submitAll() with the same result, tried querying the
table but it seems the record will not be seen until you commit the
transaction, but I cannot commit the transaction if the detail record
has not been created and correctly populated (it would be as not using
transactions and there will be a space of time in which the detail
record is not linked to it's proper master record).
My question is, how can I get the proper id value?
def addMaster(self):
db = self.masterModel.database()
row = (self.masterView.currentIndex().row()
if self.masterView.currentIndex().isValid() else 0)
db.transaction()
self.masterModel.insertRow(row)
index = self.masterModel.index(row, NAME)
self.masterView.setCurrentIndex(index)
mastertid = 1
query = QSqlQuery()
query.exec_("SELECT MAX(id) FROM master")
if query.next():
masterid = query.value(0) + 1
query.prepare("INSERT INTO detail (masterid, date, actionid) "
"VALUES (:masterid, :date, :actionid)")
query.bindValue(":masterid", masterid)
query.bindValue(":date", QDate.currentDate())
query.bindValue(":actionid", SOMEACTION)
query.exec_()
db.commit()
self.masterView.edit(index)
More information about the PyQt
mailing list