How to set default orderby in a web2py table?

白昼怎懂夜的黑 提交于 2019-12-11 19:05:46

问题


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

In the view:

def example():
    form = SQLFORM(db.foo).process()
    if form.accepted:
        redirect(URL('default', 'foo'))
    return dict(form=form)

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

回答1:


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)


来源:https://stackoverflow.com/questions/28238708/how-to-set-default-orderby-in-a-web2py-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!