如何显示QSqlRelationalTableModel InnerJoin结果

时间:2018-07-17 18:21:13

标签: python pyqt pyqt5 qsqltablemodel qsqlrelationaltablemodel

我创建了一个简单的模型来了解PyQt5中的内部联接。我的数据如下:

CREATE TABLE `admissions` (`StudentID` INTEGER PRIMARY KEY AUTOINCREMENT, `Name` TEXT, `National ID` INTEGER);
INSERT INTO `admissions` VALUES (1,'Patrick Jones',1223);
INSERT INTO `admissions` VALUES (2,'Steve Jones',1224);
CREATE TABLE `grades` (`Id` INTEGER PRIMARY KEY AUTOINCREMENT, `StudentID` INTEGER, `Math` INTEGER, `Physics` INTEGER, `Chemistry` INTEGER, `Biology` INTEGER, FOREIGN KEY(`StudentID`) REFERENCES `admissions`(`StudentID`));
INSERT INTO `grades` VALUES (1,1,56,40,35,40);
INSERT INTO `grades` VALUES (2,2,34,40,45,40);

我可以通过运行以下命令将学生成绩加入他们的名字:

SELECT admissions.Name, grades.Math, grades.Physics, grades.Chemistry FROM admissions INNER JOIN grades ON admissions.StudentID = grades.StudentID;

我已经尝试在PyQt5中执行相同的操作,但是我不能。我究竟做错了什么?我的代码:

def initializeModel(model):
    model.setTable('admissions')
    model.setJoinMode(QSqlRelationalTableModel.InnerJoin)    
    model.setRelation(0, QSqlRelation("grades", "studentid", "math"))
    #model.selectStatement()    
    model.select()

def createView(model):
   view = QTableView()
   view.setModel(model)   
   view.hideColumn(2)
   view.setColumnWidth(1, 200)
   return view

if __name__ == '__main__':

    import sys
    qApp = QApplication(sys.argv)

    db = QSqlDatabase.addDatabase('QSQLITE')
    db.setDatabaseName("drinks.db")
    db.open()

    sqm = QSqlRelationalTableModel()
    initializeModel(sqm)

    view1 = createView(sqm)

    vbox = QVBoxLayout()    
    vbox.addWidget(view1)

    window = QWidget()
    window.setLayout(vbox)
    window.setWindowTitle("Database demo 2")
    window.show()

    sys.exit(qApp.exec_())

0 个答案:

没有答案