I have a table defined in web2py
db.define_table(
'pairing',
Field('user',writable=True,readable=True),
Field('uid', writable=True , readable=True)
)
This table needs to have user and uid combination being unique. I have looked through the web2py documentation , but there isn’t direct way to define composite key .
How do we define composite way in web2py
It depends on what you are trying to do. By default, web2py automatically creates an auto-incrementing
idfield to serve as the primary key for each table, and that is the recommended approach whenever possible. If you are dealing with a legacy database with composite primary keys and cannot change the schema, you can specify aprimarykeyattribute, though with some limitations (as explained here):Perhaps instead you don’t really need a true composite primary key, but you just need some way to ensure only unique pairs of user/uid values are inserted in the table. In that case, you can do so by specifying a properly constructed
IS_NOT_IN_DBvalidator for one of the two fields:That will make sure
uidis unique among the set of records whereusermatches the new value ofuserbeing inserted (so the combination ofuseranduidmust be unique). Note, validators (such as IS_NOT_IN_DB) are only applied when values are being inserted via aSQLFORMor using the.validate_and_insert()method, so the above won’t work for arbitrary inserts into the table but is primarily intended for user input submissions.You can also use SQL to set a multi-column unique constraint on the table (which you can do directly in the database or via the web2py
.executesql()method). Even with such a constraint, though, you would still want to do some input validation within your application to avoid errors from the database.