Christophe
Christophe

Reputation: 21

web2py insert with variable table and field name e.g. with dict

Is there a way to handle table name and field name at run time ?

I have found references to an insert method that takes a dict as argument But assuming rd is a dict with 10 entries, key = name of the field, value = value to be inserted, the following code will fail

    db.OrdersFull.insert(rd)

With error :TypeError: insert() takes exactly 1 argument (2 given)
1)any clue?
2)with this solution, the table name (OrdersFull) must still be known at development time, any way to insert into a table whose name is known at run time only ?
3)Is there a place where one can found reference information for available web2py API calls ?

Upvotes: 1

Views: 320

Answers (1)

Anthony
Anthony

Reputation: 25536

To access a table based on a Python expression that yields its name, you can do:

tablename = 'mytable'
db[tablename]

This is documented here.

To use a dictionary with the .insert() method, you can use standard Python keyword argument unpacking:

db[tablename].insert(**mydict)

That is not specific to web2py or the DAL but is standard Python syntax.

There is also a special method you can use to filter out any items from the dictionary that are not fields in the table:

db.mytable.insert(**db.mytable._filter_fields(mydict))

The above is useful if you are passing in a record that was previously selected from the table, as it will automatically filter out the id field from the record (you do not want to specify an id on insert, as one will be created automatically by the database).

Regarding API reference, aside from the book, there is also this API documentation.

Upvotes: 1

Related Questions