问题
The q&a here (and the doc) describe the use of the format= argument to the define_table function. I have a problem getting that to work in a slightly more complicated case. I'm using web2py version (1, 99, 7, datetime.datetime(2012, 3, 4, 22, 12, 8), 'stable'), and Python 2.5.4. (I'm using MySQL, but I assume that's irrelevant.)
I have the following:
'Independent' (not a child) tables Institution and Person. Table Team is a child of Institution. Table Team_staff connects Person and Team together. Here's a trimmed version:
db.define_table('Person',
Field('First_name', 'string', length=60, required=True),
Field('Last_name', 'string', length=60, required=True),
...
format='%(First_name)s %(Last_name)s')
db.define_table('Institution',
Field('Institution_name', 'string', length=60, required=True,
unique=True),
format='%(Institution_name)s')
db.define_table('Team',
Field('Institution', db.Institution),
Field('Sex', 'string', required=True,
requires=IS_IN_SET(['m', 'f'])),
Field('Level', 'string', required=True),
...
format='%(Institution)s %(Sex)s')
db.define_table('Team_staff',
Field('Team', db.Team),
Field('Team_staff_member', db.Person),
...
Field('Team_position', 'string', required=True))
So far, so good. I have a controller that creates a SQLFORM(db.Team_staff), and a view that simply displays the form. When I drop down the 'Team' dropdown, I see the Institution id concatenated with the 'sex' value (such as 1 f, then 1 m below that, then 2 f, and so forth). As Institution has format='%(Institution_name)s', why am I not seeing the institution name instead of the institution id?
回答1:
The "format" attribute does not propagate across tables that way. Instead, you should be able to define the "format" attribute as a lambda function, which takes a row of the table as its argument:
db.define_table('Team', ...,
format=lambda r: '%s %s' % (db.Institution[r.Institution].Institution_name,
r.Sex))
来源:https://stackoverflow.com/questions/11267488/web2py-representation-format-in-grandchild