Results 1 to 2 of 2

Thread: Cannot insert record with QSqlRelationalTableModel

  1. #1
    Join Date
    Apr 2024
    Posts
    1
    Qt products
    Platforms
    MacOS X

    Question Cannot insert record with QSqlRelationalTableModel

    I have an application (posted below) which has a QSqlRelationalTableModel connected to a simple Sqlite db with two tables. The data from the db shows up in the QTableView as expected, which the referenced data properly filled in. However, when I try to insert a record, I get the following error:

    NOT NULL constraint failed: people.city Unable to fetch row

    It seems like the value I set in the record for the people.city field isn't making it into the insert? Any help would be appreciated. Thanks.

    Qt Code:
    1. #!/usr/bin/env python
    2.  
    3. import sys
    4. from PyQt6.QtSql import *
    5. from PyQt6.QtCore import Qt
    6. from PyQt6.QtWidgets import (QApplication, QMainWindow, QTableView)
    7.  
    8. class MainWindow(QMainWindow):
    9. def __init__(self):
    10. super().__init__()
    11.  
    12. # set up main window
    13. self.resize(1024,700)
    14.  
    15. self.model = QSqlRelationalTableModel()
    16. self.model.setTable("people")
    17. self.model.setEditStrategy(QSqlTableModel.EditStrategy.OnFieldChange)
    18. self.model.setHeaderData(2, Qt.Orientation.Horizontal, "city")
    19. self.model.setRelation(2, QSqlRelation("city", "id", "name"))
    20.  
    21. self.view = QTableView()
    22. self.view.setModel(self.model)
    23. self.view.setItemDelegate(QSqlRelationalDelegate(self.view))
    24. self.view.setSortingEnabled(True)
    25. self.view.sortByColumn(1, Qt.SortOrder.AscendingOrder)
    26. self.view.verticalHeader().setVisible(False)
    27. self.view.doubleClicked.connect(self.onAddRow)
    28.  
    29. self.setCentralWidget(self.view)
    30. self.view.resizeColumnsToContents()
    31. self.model.select()
    32.  
    33.  
    34. def onAddRow(self, s):
    35. self.model.select()
    36. new_rec = self.model.record()
    37. new_rec.setValue("name", 'Eliza')
    38. new_rec.setValue("city", 2)
    39. res = self.model.insertRecord(-1, new_rec)
    40. if res:
    41. print("insert ok")
    42. else:
    43. print("insert failed")
    44. print(self.model.lastError().text())
    45.  
    46. self.model.submitAll()
    47. self.model.select()
    48.  
    49.  
    50. # Establish connection to our database.
    51. def dbConnect():
    52. con = QSqlDatabase.addDatabase("QSQLITE")
    53. con.setDatabaseName('db.sqlite')
    54. if not con.open():
    55. print("DB connect error")
    56. sys.exit(1)
    57.  
    58. def createFakeData():
    59. query = QSqlQuery()
    60. query.exec("DROP TABLE people")
    61. query.exec("DROP TABLE city")
    62.  
    63. query.exec("CREATE TABLE people(id INTEGER PRIMARY KEY, name VARCHAR(40) NOT NULL, city INTEGER NOT NULL)")
    64. query.exec("CREATE TABLE city(id INTEGER PRIMARY KEY, name VARCHAR(40) NOT NULL)")
    65.  
    66. query.exec("INSERT INTO people(name, city) VALUES('Helen', 1)")
    67. query.exec("INSERT INTO people(name, city) VALUES('Juan', 2)")
    68. query.exec("INSERT INTO city(name) VALUES('Seattle')")
    69. query.exec("INSERT INTO city(name) VALUES('Tokyo')")
    70.  
    71.  
    72. def main():
    73. app = QApplication(sys.argv)
    74. dbConnect()
    75. createFakeData()
    76. w = MainWindow()
    77. w.show()
    78. app.exec()
    79.  
    80. if __name__ == '__main__':
    81. main()
    To copy to clipboard, switch view to plain text mode 

  2. #2
    Join Date
    Jul 2008
    Location
    Germany
    Posts
    508
    Thanks
    11
    Thanked 76 Times in 74 Posts
    Qt products
    Qt4 Qt5
    Platforms
    Unix/X11 Windows

    Default Re: Cannot insert record with QSqlRelationalTableModel

    Hi, just a wild guess: in line 19 you use setRelation to map the "id" from the "people" table to the "city" table. But when you call createFakeData() you populate the "people" table first. Maybe that causes problems, because the "city" table is still emtpy, and the mapping cannot take place?
    Does it work if you first INSERT INTO the "city" table and then into the "people" table?

    Ginsengelf

Similar Threads

  1. Insert, update database record using OOP
    By omci in forum General Programming
    Replies: 3
    Last Post: 28th January 2015, 22:21
  2. Qtablewidget insert Record from Qtableview
    By advseo32 in forum Qt Programming
    Replies: 1
    Last Post: 22nd August 2013, 10:26
  3. Replies: 4
    Last Post: 10th May 2011, 12:19
  4. Fast insert record into MySql
    By weixj2003ld in forum Qt Programming
    Replies: 3
    Last Post: 15th July 2010, 09:08
  5. Replies: 2
    Last Post: 13th April 2010, 16:50

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.