我正在使用web2py,并对如何在数据库字段定义中使用representation属性感到困惑 .
我有以下两个表定义:
my_info = db.define_table('my_info',
Field('my_uuid', 'string', length=64, requires=[IS_NOT_EMPTY()], unique=True),
Field('my_name', 'string', length=512, requires=[IS_NOT_EMPTY()]),
Field('my_type', 'string', length=32, requires=[IS_NOT_EMPTY()]),
)
my_other_info = db.define_table('my_other_info',
Field('my_other_uuid', 'string', length=64, requires=[IS_NOT_EMPTY()], unique=True),
Field('my_info_id', 'reference my_info', requires=IS_IN_DB(db, db.my_info.my_uuid, '')),
Field('my_other_name', 'string', length=512, requires=[IS_NOT_EMPTY()]),
Field('my_other_type', 'string', length=32, requires=[IS_NOT_EMPTY()]),
)
每当我访问 my_other_info
表中的 my_info_id
字段时,如果能得到 my_uuid
的值,将会有所帮助 .
我试过类似的东西:
represent=lambda id, row: db(db.my_info.id==row.my_info_id).select(db.my_info.my_uuid).first().as_dict()['my_uuid']
但这对我来说似乎没有用,我认为我对如何应对这一点有一些重大的差距 .
请注意,此应用程序中没有涉及表单处理或任何前端处理,我想使用represent属性来减少REST API中的数据库查询 .
此外,将使用命令行界面访问REST API .
我希望有人可以给我一些关于让代表工作的指示 .
谢谢,导航
1 回答
你的"represent"函数是正确的,虽然
.as_dict()
是不必要的,它可以进一步简化如下:但是,请记住"represent"属性仅在web2py通过
SQLTABLE
,SQLFORM.grid
和只读SQLFORM
编辑表单显示数据时使用 . 如果要在其他上下文中应用"represent"转换,则必须明确地执行此操作 . 一种选择是使用Rows.render()
方法:Rows
对象的.render()
方法接受一个索引并返回该记录,并将所有"represent"属性应用于其字段 . 如果没有提供索引,它将返回一个迭代器,以便您可以遍历记录 . 如果您不想转换所有字段,可以选择提供fields
参数,该参数是要转换的字段列表 .另请注意,您的
IS_IN_DB
验证程序不正确 . 因为my_info_id
字段存储db.my_info
表的记录ID,所以它应该是IS_IN_DB(db, db.my_info.id)
. 实际上,为了方便起见,你可以这样做:定义引用具有"format"属性的表的引用字段时,引用表的"format"属性用于生成缺省
IS_IN_DB
验证器和引用字段的默认"represent"属性 .