DAL Select(fields) puzzle

34 views
Skip to first unread message

Rob Paire

unread,
Aug 25, 2021, 6:39:34 PM8/25/21
to web2py-users
Hi Web2py 
I hope someone can explains this puzzling behavior. The code below was taken from the book, and it works as given, but when I remove the  "yes_or_no" condition from the field list parameters it causes a KeyError('id') error, and I don't understand why. 

    condition = db.person.name.startswith('B')
    yes_or_no = condition.case('Yes', 'No')
    rows = db(db.person.name == 'Bob').select(db.person.name,yes_or_no ).as_dict()  
    rows = db(db.person.name == 'Bob').select(db.person.ALL).as_dict()  
    ## the two select examples above works as expected

    rows = db(db.person.name == 'Bob').select(db.person.name).as_dict()  
This last example in red throws a KeyError('id') error when trying to name specific fields, but  works fine when returning ALL fields, or when a condition is specified.

Thank you
-Rob

Dave S

unread,
Aug 25, 2021, 9:44:15 PM8/25/21
to web2py-users
I don't have a complete answer, but it's the as_dict() that throws the error, because it's looking for a key that isn't there.  If you do 
for row in rows:
      print row
 you see that row doesn't have "id" as a key; it only has 'name' as a key.  as_dict() and as_list() must have a requirement for an id field, and if you make your select
rows = db(db.person.name == 'Bob').select(db.person.name,db.person,id).as_dict()
it should work as expected.
[The requirement isn't mentioned in the book]

/dps

Rob Paire

unread,
Aug 26, 2021, 3:31:31 PM8/26/21
to web2py-users
Ah! Now it makes sense - Thank you for your help. Exactly the kind of understanding I was looking for.

-Rob

Reply all
Reply to author
Forward
0 new messages