The following is in the models/db.py:
db.define_table('item_type',
Field('name'),
Field('description'),
format='%(name)s'
)
db.define_table('item',
Field('name'),
Field('description'),
Field('item_type'),
format='%(name)s'
)
db.item.item_type.requires = IS_IN_DB(db, db.item_type, '%(name)s', orderby='name')
# example fixtures
if db(db.item_type).isempty():
db.item_type.insert(name='Type1')
db.item_type.insert(name='Type2')
db.item_type.insert(name='Type3')
db.item_type.insert(name='Type10')
db.item_type.insert(name='Type20')
db.item_type.insert(name='Type30')
db.item_type.insert(name='Type99')
This will display the item_type in the following sorted order:
Type1
Type10
Type2
Type20
Type3
Type30
Type99
The following is a full example to show how to do a natural sort using alphanumeric values:
import re
def natural_key(string_):
return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_)]
db.define_table('item_type',
Field('name'),
Field('description'),
format='%(name)s'
)
db.define_table('item',
Field('name'),
Field('description'),
Field('item_type'),
format='%(name)s'
)
db.item.item_type.requires = IS_IN_DB(db, db.item_type, '%(name)s', orderby='name')
#db.item.item_type.requires = IS_EMPTY_OR(IS_IN_DB(db, db.item_type, '%(name)s', zero=None))
if db(db.item_type).isempty():
db.item_type.insert(name='Type1')
db.item_type.insert(name='Type2')
db.item_type.insert(name='Type3')
db.item_type.insert(name='Type10')
db.item_type.insert(name='Type20')
db.item_type.insert(name='Type30')
db.item_type.insert(name='Type99')
sorted_item_types = sorted(db(db.item_type.id > 0).select(), key=lambda x: natural_key(x.name))
db.item.item_type.widget = lambda f, v: SELECT([OPTION(i.name, _value=i.id) for i in sorted_item_types], _name=f.name, _id="%s_%s" % (f._tablename, f.name), _value=v, value=v)
#db.item.item_type.widget = lambda f, v: SELECT(['']+[OPTION(i.name, _value=i.id) for i in sorted_item_types], _name=f.name, _id="%s_%s" % (f._tablename, f.name), _value=v, value=v)
This will display the item_type in the following sorted order:
Type1
Type2
Type3
Type10
Type20
Type30
Type99
Note:
Use the commented lines to have a unset default/None.
Comments (0)