0

I like to access variable columns/fields of a row in SQL, how can it be done? For example, in web2py x = db(db.table.name=="john").select().last().job1 will give you the job field of the row where name equal "john". But let's say I want to choose other field/column for x in another condition like

if conditon1:
  column = job1
if condition2: 
  column = job2
x = db(db.table.name=="john").select().last().column

how can I do this?

Hans
  • 104
  • 12

2 Answers2

1

row objects can be accessed like dictionaries, so you can do:

x = db(db.table.name=="john").select().last()[column]
Anthony
  • 25,466
  • 3
  • 28
  • 57
0

Use the built-in python getattr() function

if conditon1:
  column = "job1"
if condition2: 
  column = "job2"
x = getattr(db(db.table.name=="john").select().last(), column, "Not Found")
Himel Das
  • 1,148
  • 10
  • 13
  • Using `gettatr` is not necessary, as `row` objects act as dictionaries. See https://stackoverflow.com/a/57368173/440323. – Anthony Aug 06 '19 at 02:33