如何在字段定义中使用表示

时间:2014-02-01 18:30:52

标签: rest python-2.7 web2py

我正在使用web2py,并对如何在数据库字段定义中使用represent属性感到困惑。

我有以下两个表定义:

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_uuid表格中的my_info_id字段时,如果能获得my_other_info的值,就会有所帮助。

我尝试过类似的事情:

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。

我希望有人可以给我一些关于让代表工作的指示。

谢谢, NAV

1 个答案:

答案 0 :(得分:1)

您的“代表”功能是正确的,但.as_dict()是不必要的,可以进一步简化如下:

represent=lambda id, row: db.my_info(id).my_uuid

但是,请注意,仅当web2py通过SQLTABLESQLFORM.grid和只读SQLFORM编辑表单显示数据时,才会使用“代表”属性。如果要在其他上下文中应用“表示”转换,则必须明确地执行此操作。一种选择是使用Rows.render()方法:

rows = db(db.my_other_info).select()
my_uuid = rows.render(0).my_info_id

.render()对象的Rows方法接受索引并返回该记录,并将所有“表示”属性应用于其字段。如果没有提供索引,它将返回一个迭代器,以便您可以遍历记录。如果您不想转换所有字段,可以选择提供fields参数,该参数是要转换的字段列表。

另请注意,您的IS_IN_DB验证程序不正确。由于my_info_id字段存储db.my_info表的记录ID,因此它应为IS_IN_DB(db, db.my_info.id)。实际上,为了方便起见,您可以这样做:

my_info = db.define_table('my_info',
    Field('my_uuid', 'string', length=64, requires=[IS_NOT_EMPTY()], unique=True),
    ...,
    format='%(my_uuid)s')

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'),
    ...)

当您定义引用具有“format”属性的表的引用字段时,引用表的“format”属性用于生成默认的IS_IN_DB验证器和默认的“表示”属性。参考领域。

相关问题