Setting the default of a database Field to the val

2019-04-16 01:39发布

问题:

db.define_table('mytable',
    Field('start_number', 'double', requires=IS_NOT_EMPTY()),
    Field('current_number', 'double', default=mytable.start_number, requires=IS_NOT_EMPTY()))

When something happens on the website, current_number can be changed to something else, but will always start with the default value of start_number (ie, when the entry is created). Each entry has a different start_number.

I keep getting an error saying that mytable can't be found, probably because it hasn't been fully defined yet. Is it still possible to set the default value of current_number to start_number?

回答1:

If inserts will always be done via form submissions, you could do:

Field('current_number', 'double', default=request.post_vars.start_number, ...)

Another option is to make it a computed field:

Field('current_number', 'double', compute=lambda r: r.start_number, ...)

However, by default, computed fields are not shown in forms created with SQLFORM, so if you want to display the field in an update form, you will have to explicitly specify the fields to show on the form or temporarily set the field's "compute" attribute to None.



标签: python web2py