How to access raw value of foreign key?
-
Given a
QSqlRelationalTableModel
I just want to cycle among all the columns and get the actual raw values, not the one of the related table. Example:QSqlRelationalTableModel *model; // select the model for (int row = 0; row < model->rowCount(); row++) { for (int col = 0; col < model->columnCount(); col++) { qDebug() << model->data(_model->index(row, col), Qt::EditRole); } }
This code still prints the related value.
So I tried to retrieve it in the hard way:QString displayValue = model->data(model->index(row, col)).toString(); QSqlTableModel *m = model->relationModel(col); if (m) { QSqlRelation r = model->relation(col); m->setFilter(QString("%1=%2").arg(r.displayColumn(), displayValue)); qDebug() << m->fieldIndex(r.displayColumn()) << displayValue << m->rowCount(); } else qDebug() << model->data(model->index(row, col));
The idea is to filter the related model using the
displayColumn()
and thedisplayValue
so I can then retrieve the correct row. Even if the printed filter values are correct, therowCount()
is always 0.After a search I found other users surrendered to make direct SQL queries. But it must be a "Qt-way" to get the actual value of the model.
-
Given a
QSqlRelationalTableModel
I just want to cycle among all the columns and get the actual raw values, not the one of the related table. Example:QSqlRelationalTableModel *model; // select the model for (int row = 0; row < model->rowCount(); row++) { for (int col = 0; col < model->columnCount(); col++) { qDebug() << model->data(_model->index(row, col), Qt::EditRole); } }
This code still prints the related value.
So I tried to retrieve it in the hard way:QString displayValue = model->data(model->index(row, col)).toString(); QSqlTableModel *m = model->relationModel(col); if (m) { QSqlRelation r = model->relation(col); m->setFilter(QString("%1=%2").arg(r.displayColumn(), displayValue)); qDebug() << m->fieldIndex(r.displayColumn()) << displayValue << m->rowCount(); } else qDebug() << model->data(model->index(row, col));
The idea is to filter the related model using the
displayColumn()
and thedisplayValue
so I can then retrieve the correct row. Even if the printed filter values are correct, therowCount()
is always 0.After a search I found other users surrendered to make direct SQL queries. But it must be a "Qt-way" to get the actual value of the model.
@Mark81 said in How to access raw value of foreign key?:
Even if the printed filter values are correct, the rowCount() is always 0.
This was simple:
m->setFilter(QString("%1='%2'").arg(r.displayColumn(), displayValue));
did the trick. Followed by:
qDebug() << m->data(m->index(0, m->fieldIndex(r.indexColumn())));
seems to solve the issue.
Is my approach correct or is there anything better?