Search code examples
web2py

Making a function to abstract a web2py DB call


I'm using web2py with its DAL. I want to do a function (for several reasons as code readability, abstracting from web2py…) that will perform a select on the DB. For instance:

def get_element_from_id(id, *options):
  return db(db.element.id == id).select(options)

The function is quite basic but it doesn't work. If I provide no option (just calling get_element_from_id(1)), I have a wonderful:

AttributeError: 'tuple' object has no attribute 'type'

If I provide an option (for instance get_element_from_id(1, db.element.id)), I get a:

AttributeError: 'NoneType' object has no attribute 'startswith'

Any idea? Thanks in advance!


Solution

  • In the function, options will be a list, but .select() does not take a list, so you must use the * notation to expand the list into a set of arguments:

    .select(*options)
    

    Also, to make the function more general, you might also want to allow the keyword arguments of the .select() method -- so:

    def get_element_from_id(id, *args, **kwargs):
        return db(db.element.id == id).select(*args, **kwargs)
    

    Also, note that if you just want to retrieve the whole record based on the ID, the DAL already allows you to do this:

    db.element(id)