foreign-key-relationshippyqt5qtsql

How to get the indexvalue of a column with a relation set in QSqlRelationalTableModel?


In QsqlRelationalTableModel foreign keys are resolved to human readable strings, if a relation for the column containing a foreign key is set. In my application stationids are resolved to stationnames.

For some purposes i need the stationid too. QsqlRelationalTableModel.data() or QsqlRelationalTableModel.itemData() only return the displayValue (for displayrole as well as for editrole). How can i get the corresponding foreign key (indexValue)?


Solution

  • QsqlRelationalTableModel.relationModel() returns a QSqlTableModel object for accessing the table for which column is a foreign key.

    http://doc.qt.io/qt-5/qsqlrelationaltablemodel.html#relationModel

    By the setFilter() method of relationModel() the corresponding id (indexValue) can be found, if the displayValue is unique:

    rm = self.relationModel(<index column>)
    f = '<columnname> = "{}"'.format(<displayvalue>)
    rm.setFilter(f)
    id = rm.data(rm.index(0,0))