Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Qt for Python
  4. How to insert data into a QSqlRelationalTableModel ?

How to insert data into a QSqlRelationalTableModel ?

Scheduled Pinned Locked Moved Solved Qt for Python
6 Posts 2 Posters 700 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J Offline
    J Offline
    judethedude
    wrote on 28 Sept 2022, 21:16 last edited by judethedude
    #1

    Hey everyone,

    For the life of me, I cannot figure out how to insert data into a QSqlRelationalTableModel.
    Model:

    class ApptTableModel(QSqlRelationalTableModel):
        def __init__(self):
            super().__init__()
            self.setTable('appointments')
            self.setRelation(1, QSqlRelation("patient_profile", "id", "id, name_fname, name_lname"))
            self.setEditStrategy(QSqlTableModel.OnRowChange)
            self.select()
    
        def insert_into_model(self, update_row: int, data):
                """Set update_row to -1 if inserting new data, else set to row"""
                rec = self.record()
                for col in range(6):
                    rec.setValue(col, data[col])
                    print(rec.value(col))
                self.insertRecord(self.rowCount(), rec)
                self.select()
    

    View:

    class ApptView(QWidget):
        def __init__(self, parent, appt_model, patient_model, patient_proxy_model):
            super().__init__(parent)
    
            self.appt_ui = Ui_appt_form()
            self.appt_ui.setupUi(self)
            self.appt_ui.appt_tableview.setModel(self._appt_model)
            # ^model already intialized and passed in from parent QWidget
            self.appt_ui.appt_tableview.setItemDelegate(QSqlRelationalDelegate(self.appt_ui.appt_tableview))
            # ^this line doesn't seem to do anything but was recommended from StackOverflow?
        
        def add_appointment(self, update: bool):
                if len(self.appt_ui.patient_search_tableView.selectionModel().selectedRows()):
                    appt_data = [
                        self._selected_patient_id,
                        self.appt_ui.calendarWidget.selectedDate().toString(Qt.ISODate),
                        self.appt_ui.appt_time_spin.time().toString(Qt.ISODate),
                        self.appt_ui.appt_duration_spin.value(),
                        self.appt_ui.appt_reason.text(),
                        self.appt_ui.appt_notes.toPlainText()
                    ]
                    print(appt_data)
                    if not update:
                        self._appt_model.insert_into_model(-1, appt_data)
    

    I've tried preparing a record and inserting it, tried calling setData. Both of which work fine without
    self.setRelation(1, QSqlRelation("patient_profile", "id", "id, name_fname, name_lname"))

    I should mention, the tableview shows the foreign columns just fine, it's just the inserting (or updating) of data that I can't get to work.

    Any help at all would be greatly appreciated.

    EDIT: Essentially, this (unanswered) StackOverflow question: here, his example is simpler

    J 1 Reply Last reply 28 Sept 2022, 22:25
    0
    • J judethedude
      28 Sept 2022, 21:16

      Hey everyone,

      For the life of me, I cannot figure out how to insert data into a QSqlRelationalTableModel.
      Model:

      class ApptTableModel(QSqlRelationalTableModel):
          def __init__(self):
              super().__init__()
              self.setTable('appointments')
              self.setRelation(1, QSqlRelation("patient_profile", "id", "id, name_fname, name_lname"))
              self.setEditStrategy(QSqlTableModel.OnRowChange)
              self.select()
      
          def insert_into_model(self, update_row: int, data):
                  """Set update_row to -1 if inserting new data, else set to row"""
                  rec = self.record()
                  for col in range(6):
                      rec.setValue(col, data[col])
                      print(rec.value(col))
                  self.insertRecord(self.rowCount(), rec)
                  self.select()
      

      View:

      class ApptView(QWidget):
          def __init__(self, parent, appt_model, patient_model, patient_proxy_model):
              super().__init__(parent)
      
              self.appt_ui = Ui_appt_form()
              self.appt_ui.setupUi(self)
              self.appt_ui.appt_tableview.setModel(self._appt_model)
              # ^model already intialized and passed in from parent QWidget
              self.appt_ui.appt_tableview.setItemDelegate(QSqlRelationalDelegate(self.appt_ui.appt_tableview))
              # ^this line doesn't seem to do anything but was recommended from StackOverflow?
          
          def add_appointment(self, update: bool):
                  if len(self.appt_ui.patient_search_tableView.selectionModel().selectedRows()):
                      appt_data = [
                          self._selected_patient_id,
                          self.appt_ui.calendarWidget.selectedDate().toString(Qt.ISODate),
                          self.appt_ui.appt_time_spin.time().toString(Qt.ISODate),
                          self.appt_ui.appt_duration_spin.value(),
                          self.appt_ui.appt_reason.text(),
                          self.appt_ui.appt_notes.toPlainText()
                      ]
                      print(appt_data)
                      if not update:
                          self._appt_model.insert_into_model(-1, appt_data)
      

      I've tried preparing a record and inserting it, tried calling setData. Both of which work fine without
      self.setRelation(1, QSqlRelation("patient_profile", "id", "id, name_fname, name_lname"))

      I should mention, the tableview shows the foreign columns just fine, it's just the inserting (or updating) of data that I can't get to work.

      Any help at all would be greatly appreciated.

      EDIT: Essentially, this (unanswered) StackOverflow question: here, his example is simpler

      J Offline
      J Offline
      JonB
      wrote on 28 Sept 2022, 22:25 last edited by
      #2

      @judethedude
      To be clear, both you and the SO topic you reference are trying to use multiple columns from the foreign key table. I believe that is not "supported" by the Qt code, it is "fortunate" that it works when selecting rows but not if attempting to update the table.

      I presume if you reduce to:

      self.setRelation(1, QSqlRelation("patient_profile", "id", "id"))
      

      (or any one of the 3 foreign columns) then your updates work OK?

      J 1 Reply Last reply 28 Sept 2022, 23:42
      1
      • J JonB
        28 Sept 2022, 22:25

        @judethedude
        To be clear, both you and the SO topic you reference are trying to use multiple columns from the foreign key table. I believe that is not "supported" by the Qt code, it is "fortunate" that it works when selecting rows but not if attempting to update the table.

        I presume if you reduce to:

        self.setRelation(1, QSqlRelation("patient_profile", "id", "id"))
        

        (or any one of the 3 foreign columns) then your updates work OK?

        J Offline
        J Offline
        judethedude
        wrote on 28 Sept 2022, 23:42 last edited by
        #3

        @JonB Dang. Yes, reducing to a one-to-one works, but I was hoping to reduce redundant info in my table. Doesn't really matter though, I'll pursue it the way you suggested!

        J 1 Reply Last reply 29 Sept 2022, 07:05
        0
        • J judethedude
          28 Sept 2022, 23:42

          @JonB Dang. Yes, reducing to a one-to-one works, but I was hoping to reduce redundant info in my table. Doesn't really matter though, I'll pursue it the way you suggested!

          J Offline
          J Offline
          JonB
          wrote on 29 Sept 2022, 07:05 last edited by JonB
          #4

          @judethedude
          Well, to be clear I did not really suggest a "way" forward. You can have multiple QRelations on a QSqlRelationalTableModel but only if they reference different columns in the referring table, you cannot have more than one on the same column. So you cannot do yours that way. The "workaround" of specifying a comma-separated list ("id, name_fname, name_lname") is, I believe, not documented or supported. I suspect people came across it "by coincidence". It may be that it "works" because you can just paste that string into the middle of a SELECT statement, but when trying to generate INSERT or UPDATE statements it is not good enough.

          Which leaves you with, I believe: if you use a multi-column QSqlRelation you can read but not update the table, and I don't have something which works for updating.

          J 1 Reply Last reply 29 Sept 2022, 11:59
          0
          • J JonB
            29 Sept 2022, 07:05

            @judethedude
            Well, to be clear I did not really suggest a "way" forward. You can have multiple QRelations on a QSqlRelationalTableModel but only if they reference different columns in the referring table, you cannot have more than one on the same column. So you cannot do yours that way. The "workaround" of specifying a comma-separated list ("id, name_fname, name_lname") is, I believe, not documented or supported. I suspect people came across it "by coincidence". It may be that it "works" because you can just paste that string into the middle of a SELECT statement, but when trying to generate INSERT or UPDATE statements it is not good enough.

            Which leaves you with, I believe: if you use a multi-column QSqlRelation you can read but not update the table, and I don't have something which works for updating.

            J Offline
            J Offline
            judethedude
            wrote on 29 Sept 2022, 11:59 last edited by
            #5

            @JonB Yeah I understand. I just mean I will restructure my appointment table to have something like "patient_id", "patient_fname_id" etc...

            Thanks for your responses.

            J 1 Reply Last reply 29 Sept 2022, 12:02
            0
            • J judethedude
              29 Sept 2022, 11:59

              @JonB Yeah I understand. I just mean I will restructure my appointment table to have something like "patient_id", "patient_fname_id" etc...

              Thanks for your responses.

              J Offline
              J Offline
              JonB
              wrote on 29 Sept 2022, 12:02 last edited by
              #6

              @judethedude said in How to insert data into a QSqlRelationalTableModel ?:

              I will restructure my appointment table to have something like "patient_id", "patient_fname_id" etc...

              Yeah, it is ugly to have to do that. You ought not need to change your database tables to keep client software happy. But I see your problem!

              1 Reply Last reply
              1

              1/6

              28 Sept 2022, 21:16

              • Login

              • Login or register to search.
              1 out of 6
              • First post
                1/6
                Last post
              0
              • Categories
              • Recent
              • Tags
              • Popular
              • Users
              • Groups
              • Search
              • Get Qt Extensions
              • Unsolved