如何将 id 转换为 Web2py 中的引用字段? [英] How to convert id into referenced field in Web2py?
问题描述
考虑下面的 3 个表 (A
, B
& C
),其中表 C
有 2 个字段参考表 A
和 B
.
Consider the 3 tables below (A
, B
& C
) where table C
has 2 fields referenced to table A
and B
.
型号:
db.define_table('A',
Field('A1', 'string', required =True),
Field('A2', 'string', required =True),
Field('A3', 'string', required =True),
format=lambda r: '%s, %s' % (r.A.A1, r.A.A2))
db.define_table('B',
Field('B1', 'string', required=True),
Field('B2', 'string', required=True),
Field('B3', 'string', required=True),
format=lambda r: '%s, %s' % (r.B.B1, r.B.B2))
db.define_table('C',
Field('C1', db.A),
Field('C2', db.B),
Field('C3', 'string', required=True),
format=lambda r: '%s, %s - %s' % (r.C.C1, r.C.C2))
控制器:
def C_view():
if request.args(0) is None:
rows = db(db.C).select(orderby=db.C.C1|db.C.C2)
else:
letter = request.args(0)
rows = db(db.C.C1.startswith(letter)).select(orderby=db.C.C1|db.C.C2)
return locals()
在下面的相应视图中,我显示了表 C 的 3 个字段:
In the corresponding view below I display the 3 fields of table C:
...
{{ for x in rows:}}
<tr>
<td>{{=x.C1}}</td>
<td>{{=x.C2}}</td>
<td>{{=x.C3}}</td>
</tr>
{{pass}}
...
通过此设置,视图显示 C1 & 的外部 ID.C2.我将如何修改模型、控制器和/或视图以显示相应的参考字段而不是 ID?换句话说:对于 C1
视图应该显示 rAA1, rAA2
而对于 C2
视图应该显示 rBB1, rBB2
>.
With this setup, the view displays the foreign id of C1 & C2. How would I have to modify the model, controller and/or the view to display the corresponding reference fields rather than the id's? In other words:
for C1
the view should display r.A.A1, r.A.A2
and for C2
the view should display r.B.B1, r.B.B2
.
谢谢.
推荐答案
你需要正确使用format: Record representation
并使用 render()code> 将 id 转换为它们各自的表示形式.
You need to use format: Record representation
correctly and use render()
to convert ids into their respective representation.
您的模型将如下所示:
db.define_table('A',
Field('A1', 'string', required=True),
Field('A2', 'string', required=True),
Field('A3', 'string', required=True),
format='%(A1)s, %(A2)s')
db.define_table('B',
Field('B1', 'string', required=True),
Field('B2', 'string', required=True),
Field('B3', 'string', required=True),
format='%(B1)s, %(B2)s')
db.define_table('C',
Field('C1', db.A),
Field('C2', db.B),
Field('C3', 'string', required=True))
并更新控制器并使用render().render() 返回一个生成器来迭代所有行.
And update controller and use render(). render() returns a generator to iterate over all rows.
def C_view():
if request.args(0) is None:
rows = db(db.C).select(orderby=db.C.C1|db.C.C2).render()
else:
letter = request.args(0)
rows = db(db.C.C1.startswith(letter)).select(orderby=db.C.C1|db.C.C2).render()
return locals()
参考:
这篇关于如何将 id 转换为 Web2py 中的引用字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!