我有两个SQLite表,具有以下结构:
CREATE TABLE "log" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"name" TEXT,
"value" INTEGER NOT NULL,
"category_id" INTEGER NOT NULL,
"date" TEXT NOT NULL,
FOREIGN KEY("category_id") REFERENCES "category"("id")
);
CREATE TABLE "category" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"category_name" TEXT NOT NULL,
"type" TEXT NOT NULL
);
我还想显示使用QSqlRelationalTableModel
的QTableView
。我需要显示两列(category_name
和type
(而不是category_id
,尽管QSqlRelation似乎只用一列替换了外键,但我还是显示了两列,如下所示:
self.balance_table_model = QSqlRelationalTableModel()
self.balance_table_model.setTable("log")
self.balance_table_model.setRelation(3, QSqlRelation("category", "id", "category_name, type"))
self.balance_table_model.setHeaderData(1, Qt.Horizontal, "Name")
self.balance_table_model.setHeaderData(2, Qt.Horizontal, "Value")
self.balance_table_model.setHeaderData(3, Qt.Horizontal, "Category")
self.balance_table_model.setHeaderData(4, Qt.Horizontal, "Type")
self.balance_table_model.setHeaderData(5, Qt.Horizontal, "Date")
self._ui.balanceTableView.setModel(self.balance_table_model)
self._ui.balanceTableView.setColumnHidden(0, True)
现在,当我想添加新行时,只有当我连接两个没有类型的表时,插入才有效,即
self.balance_table_model.setRelation(3, QSqlRelation("category", "id", "category_name"))
插入代码:
record = self.balance_table_model.record()
record.setGenerated(0, True)
record.setValue(1, log_name)
record.setValue(2, log_value)
record.setValue(3, category_id)
record.setValue(4, date)
self.balance_table_model.insertRecord(-1, record)
如何在仍然能够显示type
列的情况下使插入工作?
遇到了完全相同的问题。不幸的是,Qt不支持多列,所以我们只需要为每列建立一对一的关系:
self.balance_table_model.setRelation(3, QSqlRelation("category", "id", "category_name"))
来源:https://forum.qt.io/topic/139659/how-to-insert-data-into-a-qsqlrelationaltablemodel
编辑:我有一个类似的例子:
create_table_query.exec(
"""CREATE TABLE "appointments" (
"appt_id" INTEGER,
"patient_id" INTEGER,
"patient_fname_id" INTEGER,
"patient_lname_id" INTEGER,
"scheduled_date" TEXT,
"scheduled_time" TEXT,
"scheduled_duration" INTEGER,
"reason" TEXT,
"appt_notes" TEXT,
PRIMARY KEY("appt_id"),
FOREIGN KEY("patient_id") REFERENCES "patient_profile"("patient_id")
)
""")
然后我设置
"patient_id" INTEGER,
"patient_fname_id" INTEGER,
"patient_lname_id" INTEGER,
全部为"0"的值;patient_id";在我的QWidget视图中,因此一个平均的数据库条目如下所示:此处
我的模型和关系如下:
class ApptTableModel(QSqlRelationalTableModel):
def __init__(self):
super().__init__()
self.setTable('appointments')
self.setRelation(1, QSqlRelation("patient_profile", "patient_id", "patient_id"))
self.setRelation(2, QSqlRelation("patient_profile", "patient_id", "name_fname"))
self.setRelation(3, QSqlRelation("patient_profile", "patient_id", "name_lname"))
这是一个有点麻烦的解决方案(以及数据库表中令人讨厌的冗余值(,但它现在运行得很完美。