composite key in web2py

前端 未结 2 1382
慢半拍i
慢半拍i 2021-01-07 03:00

I have a table defined in web2py

db.define_table(
\'pairing\',
Field(\'user\',writable=True,readable=True),
Field(\'uid\', writable=True , readable=True)
)
<         


        
2条回答
  •  囚心锁ツ
    2021-01-07 04:01

    It depends on what you are trying to do. By default, web2py automatically creates an auto-incrementing id field 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 a primarykey attribute, though with some limitations (as explained here):

    db.define_table('pairing', 
        Field('user', writable=True, readable=True), 
        Field('uid', writable=True, readable=True),
        primarykey=['user', 'uid'])
    

    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_DB validator for one of the two fields:

    db.define_table('pairing',
        Field('user', writable=True, readable=True),
        Field('uid', writable=True, readable=True))
    
    db.pairing.uid.requires=IS_NOT_IN_DB(db(db.pairing.user==request.vars.user),
        'pairing.uid')
    

    That will make sure uid is unique among the set of records where user matches the new value of user being inserted (so the combination of user and uid must be unique). Note, validators (such as IS_NOT_IN_DB) are only applied when values are being inserted via a SQLFORM or 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.

提交回复
热议问题