简体   繁体   中英

Iterate though an sqlalchemy ORM record

I have a sqllite data table created with sqlalchemy that i would like to represent on a PyQt5 tablewidget.

    def createTable(self, tableData):
      self.qTable = session.query(tableData).all()
      self.tableWidget = QTableWidget()
      self.tableWidget.setRowCount(0)
      self.tableWidget.setColumnCount(tableData.cols)
      self.tableWidget.setHorizontalHeaderLabels(tableData.col_headers)
      for row, form in enumerate(self.qTable):
        self.tableWidget.setRowCount(row+1)
           for col,record in enumerate(form):
                self.tableWidget.setItem(row, col, QTableWidgetItem(record))

This breaks at the line

for col,record in enumerate(form):

with an error "TypeError: 'Tests' object is not iterable"

The ORM is built with this code

class Tests(Base):
  __tablename__ = 'tests'
  id = Column(Integer, primary_key=True)
  current = Column(Boolean)
  temp = Column(Float)
  brine = Column (Float)
  test = Column(String)
  pc = Column(Float)
  wait_time = Column(Integer)
  headers = {"current","temp","brine","test","pc","wait time"}

is there a way to make this iterable? or a neater way of dealing with this??

Thanks @SuperShoot, this worked pretty well for me here is the final code I used

 for row, form in enumerate(self.qTable):
        col = 0
        self.tableWidget.setRowCount(row+1)
        for c in columns:
            for k,v in vars(form).items():
                if k == c:
                    self.tableWidget.setItem(row, col, QTableWidgetItem(str(v)))
                    col +=1

I added extra logic so i can define the column order,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM