[prev in list] [next in list] [prev in thread] [next in thread]
List: pykde
Subject: [PyQt] QRelationalTableModel usage question
From: Ricardo Araoz <ricaraoz () gmail ! com>
Date: 2018-04-11 0:15:54
Message-ID: c8d584bd-470f-b294-0dc3-a6b97179ad3a () gmail ! com
[Download RAW message or body]
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)
_______________________________________________
PyQt mailing list PyQt@riverbankcomputing.com
https://www.riverbankcomputing.com/mailman/listinfo/pyqt
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic