Search code examples
web2pyrepresentation

Web2py: use Field represent without SQLFORM


In Web2py you can assign lambda to database Field to represent it as text: Field('duetime', 'time', represent=lambda t,r: t.strftime("%H:%M") if t else '') With such description when generating SQLForm you will get nice time representation (seconds will not be shown).

But when I want to use data representation in plain HTML view, I get only raw data: for r in rows: print "Repr: %s Str: %s" % (r.duetime.repr(),r.duetime.str()) Repr: datetime.time(16, 15) Str: 16:15:00 Repr: None Str: None So it looks like only SQLForm internally generates field representations. How can I get query result set (Rows) containing data representation instead of raw data?


Solution

  • You can use the Rows.render method. For a single record:

    rows = db(query).select()
    rendered_row = rows.render(0) # apply "represent" functions to the first row
    print rendered_row.duetime
    

    For efficiency, you can limit to which fields the "represent" functions will be applied:

    rendered_row = rows.render(0, fields=[db.mytable.duetime])
    

    If you don't pass an index as the first argument to .render(), it returns a generator, allowing you to loop over all rows:

    for row in rows.render():
        print row.duetime
    

    If you want to loop over a subset of the rows, create the subset and call .render() on the subset:

    for row in rows[0:10].render():
        print row.duetime
    

    Details in the book.