user174916
user174916

Reputation: 97

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?

Upvotes: 1

Views: 1349

Answers (2)

Anthony
Anthony

Reputation: 25536

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.

Upvotes: 2

user174916
user174916

Reputation: 97

Ok, I wrote little function that takes Rows and Table as arguments and returns list of dictionaries, where keys are fields and values are their representations (almost like Rows): def get_rows_representation(rows,table): return [{f: table[f].represent(r[f],r) if table[f].represent else r[f] for f in r.as_dict()} for r in rows]

But maybe there is a better native way to directly get Field representation from Rows?

Upvotes: 0

Related Questions