I have a table defined in web2py
db.define_table(
\'pairing\',
Field(\'user\',writable=True,readable=True),
Field(\'uid\', writable=True , readable=True)
)
<
I have been using a computed field to create/simulate a composite key. Taking the example from the above question, one can define the junction table as follows:
from md5 import md5
db.define_table( 'pairing',
Field('user', writable=True, readable=True),
Field('uid', writable=True, readable=True),
Field( 'user_uid_md5',
length=32,
unique=True,
writable=False,
readable=False,
compute=lambda row: md5("{0}:{1}".format(row.user,row.uid)).hexdigest()))
The user_uid_md5
field is automatically computed on insert and updates. The value of this field is the md5 hash of a string obtained from the two fields user
and uid
. This field is also marked as unique
. So the database enforces uniqueness here and this works around the limitation pointed out by Anthony. This should also work to emulate composite keys with more than two fields. If you see any holes in this approach, please let me know.
Edit: Slight update to the way the md5 hash is computed to account for the case pointed out by Chen Levy in a comment below.