Multi-Column Unique Constraint with web2py

房东的猫 提交于 2019-12-05 02:21:11

Assuming the data will be entered via a form, you could use a form validator, like this:

db.define_table('rates',
    Field('from_currency'),
    Field('to_currency'))

db.rates.to_currency.requires=IS_NOT_IN_DB(
    db(db.rates.from_currency==request.vars.from_currency), 'rates.to_currency')

That will make sure to_currency is unique among the set of records where from_currency matches the new value of from_currency being inserted (so the combination of from_currency and to_currency must be unique).

Another option is to use an onvalidation function to confirm the two values are distinct -- this will run after the usual form validation, but before the DB insert.

Finally, you could instead do the validation client-side via Javascript.

Diogo Martins

You could also try using the Before and After callbacks. Using Anthony's table as an example, you would do something like:

db.rates._before_insert.append( lambda r : db( (db.rates.from_currency==r["from_currency"]) & (db.rates.to_currency==r["to_currency"]) ).select() )

If the .select() query returns anything but None or False, it will abort the current db.rates.insert() and give False as a return . Notice that it still won't create an UNIQUE CONSTRAINT, but its way more safe than using some client-side validation.

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