Iif you want virtual fields to show up in a query over a single table they 
have to be defined in that table, otherwise you need to join a table where 
they exist.

The definition of a virtual field needs a name and usually a lambda 
function over fields in a row.
Lets add a virtual field to the auth_user table:

db.auth_user.full_name = Field.Virtual('full_name', lambda row: '%s %s' %(
row.auth_user.first_name, row.auth_user.last_name))

Now everytime you retrieve rows from auth_user, whether directly or via a 
join, they will have a field called full_name.

There are also Method fields which are functions than can be called to 
obtain a value.

db.items.createdbyfullname = Field.Method('createdbyfullname', 
  lambda row: db(db.auth_user.id==row.items.created_by).select()[0].
full_name)

So now, after retrieving rows from item, you can call the row's 
createdbyfullname function to get the full name of the user that created 
the entry.

Note that is over simplified but helps to illustrate the use.

Denes





On Thursday, January 21, 2016 at 5:24:00 PM UTC-5, Oliva Lemke wrote:
>
> hi
>
> i have table
> db.define_table('items', Field('name'), Field('created_by'), 
> Field('modified_by'))
>
> fields `created_by` and `modified_by` has defined relation to 
> db.auth_user.user_id (not auth_user.id)
>
> how to programatically create virtual fields created_by.full_name and 
> modified_by.full_name?
>
>
>         lefts = []
>         auth_user_fields = ('created_by', 'modified_by')
>         for field in auth_user_fields:
>             table = db.auth_user.with_alias(field)
>             table.full_name = self.db.Field.Virtual('full_name', lambda 
> row, field=field: '%s %s' % (row[field].first_name, row[field].last_name))
>             lefts.append(table.on(table.user_id==self.model[field]))
>
>         rows = db(db.items).select(left=lefts)
>
> but `rows` in last line contains only fields/columns from `db.items` , 
> aliased `created_by` and `modified_by` `auth_user` table is missing
>
> am i doing something wrong?
>

-- 
Resources:
- http://web2py.com
- http://web2py.com/book (Documentation)
- http://github.com/web2py/web2py (Source code)
- https://code.google.com/p/web2py/issues/list (Report Issues)
--- 
You received this message because you are subscribed to the Google Groups 
"web2py-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to web2py+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to