Python peewee - select from multiple tables
Asked Answered
I

1

8

I am trying to select two fields from separate tables using peewee. I believe my issue is with iterating over the resulting object.

I have the following code in Python:

sHeader_Value = (System_Headers
  .select(System_Headers.SystemHeader_Name, System_Data.System_Value)
  .join(System_Header_Link)
  .join(System_Data_Link)
  .join(System_Data))

That code generates the following SQL:

SELECT t1.`SystemHeader_Name`, t4.`System_Value` 
FROM `system_headers` AS t1
INNER JOIN `system_header_link` AS t2 ON (t1.`SystemHeader_ID` = t2.`SystemHeader_ID`) 
INNER JOIN `system_data_link` AS t3 ON (t2.`SystemHeaderLink_ID` = t3.`SystemHeaderLink_ID`)
INNER JOIN `system_data` AS t4 ON (t3.`SystemData_ID` = t4.`SystemData_ID`)

Executing that in MySQL Workbench I get a table with two fields: SystemHeader_Name, System_Value.

I'm trying to figure out how to get the System_Value from the query wrapper. If I do the following:

for s in sHeader_Value:
  print s.SystemHeader_Name, s.System_Value

I am presented with an AttributeError, stating that the 'System_Headers' object has no attribute 'System_Value'.

Note that if I only try to do print s.SystemHeader_Name, it executes flawlessly.

How do I capture the values for my System_Value field?

Idolatrous answered 14/10, 2013 at 17:46 Comment(0)
I
9

I just figured out what the issue was. The data object it returns is a System_Headers object, which is the model for that specific table. As such, that model does not have a System_Value attribute. By adding naive() to my peewee code it passed the attribute onto my System_Headers model, thus allowing me to access the System_Value field.

Below is the working code:

sHeader_Value = (System_Headers
  .select(System_Headers.SystemHeader_Name, System_Data.System_Value)
  .join(System_Header_Link)
  .join(System_Data_Link)
  .join(System_Data)
  .naive())
Idolatrous answered 14/10, 2013 at 18:31 Comment(3)
Yes, this worked. But when I serialize the row it does not add the System_Value keyMylander
Anyone know how to get around this issue when using a LEFT OUTER JOIN it still gives out the same error.Lepsy
Naive is not replaced with objects() docs.peewee-orm.com/en/latest/peewee/changes.htmlDodge

© 2022 - 2024 — McMap. All rights reserved.