如何在web2py表中设置默认orderby?

2024-04-27 04:13:11 发布

您现在位置:Python中文网/ 问答频道 /正文

虽然我认为这是一个简单的任务,但在使用SQLFORM时,我找不到使其工作的方法。以这个结构为例:

db.define_table('month',
    Field('name', 'string'),
    format='%(nombre)s'
)

db.define_table('foo'
    Field('bar', 'string'),
    Field('month', db.month), # I want to sort this by ID
    format='%(bar)s'
)

db.month.update_or_insert(id=1, nombre='January')
db.month.update_or_insert(id=2, nombre='Frebruary')
# ...
db.month.update_or_insert(id=12, nombre='December')

在视图中:

^{pr2}$

form正在按字母顺序对月份进行排序,这不是desire行为,我想显示按ID排序的月份。有没有方法在表中设置默认顺序?在

db.month.orderby = db.month.id # Not working
db.month._orderby = db.month.id # Not working

Tags: or方法idformatfielddbstringtable
1条回答
网友
1楼 · 发布于 2024-04-27 04:13:11

db.foo.month字段是一个引用字段,默认情况下,它获得一个IS_IN_DB验证器,这将导致在表单中生成select小部件。select小部件包含“month”表记录的id作为值,但是由于db.month表的“format”属性,它在下拉列表中显示月份名称。默认情况下,下拉列表中的项目最终按格式字符串(在本例中是月份名称)中指定的字段排序。要改变这种情况,您可以手动定义验证器并指定“orderby”参数:

db.foo.month.requires = IS_IN_DB(db, 'month.id', db.month._format,
                                 orderby=db.month.id)

相关问题 更多 >