问题描述
尽管我认为这是一个简单的任务,但是在使用SQLFORM
时我找不到找到使其工作的方法.假设我以这个结构为例:
Although I consider this a simple task I can't find a way to make it work when using a SQLFORM
. Let's say I have this structure as an example:
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')
在视图中:
def example():
form = SQLFORM(db.foo).process()
if form.accepted:
redirect(URL('default', 'foo'))
return dict(form=form)
form
按字母顺序对月份进行排序,这不是期望的行为,我想显示按ID排序的月份.有没有办法在表格中设置默认顺序?
The form
is sorting the months alphabetically and that is not the desire behavior, I want to show the months ordered by ID. Is there a way to set the default order in a table?
db.month.orderby = db.month.id # Not working
db.month._orderby = db.month.id # Not working
推荐答案
db.foo.month
字段是一个参考字段,默认情况下,它会获得一个IS_IN_DB
验证器,该验证器将以以下形式生成选择窗口小部件. select小部件包括月"表记录的ID作为值,但是由于db.month
表的格式"属性,因此它在下拉列表中显示月名称.默认情况下,下拉列表中的项目最终由格式字符串中指定的字段(在本例中为月份名称)排序.要更改此设置,您可以手动定义验证器并指定"orderby"参数:
The db.foo.month
field is a reference field, and by default, it gets an IS_IN_DB
validator, which results in the select widget being generated in the form. The select widget includes the IDs of the "month" table records as values, but it displays the month names in the dropdown because of the "format" attribute of the db.month
table. By default, the items in the dropdown end up being ordered by the fields specified in the format string (in this case, the month names). To change that, you can manually define the validator and specify the "orderby" argument:
db.foo.month.requires = IS_IN_DB(db, 'month.id', db.month._format,
orderby=db.month.id)
这篇关于如何在web2py表中设置默认orderby?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!