Question

I see from web2py DAL document that to add a foreign key reference to a field, I have to specify

db.define_table('thing',
                Field('name'),
                Field('owner_id', 'reference person'))

Where person's schema will be

db.define_table('person',
                Field('name'),
                format='%(name)s')

The problem with this reference syntax is that, it, by default, assumes id to the referenced field in the base table. Supposing I want some attribute in the thing table to refer to the person's name attribute (or any attribute other than id), is there a way to do so?

I am working with a legacy database which has an id by itself and this id cannot be reset with the id field that web2py creates.

Was it helpful?

Solution

Tables created by web2py use the "id" field as the primary key, so reference fields set a foreign key constraint referencing the "id" field.

If the primary key in your legacy database table is an auto-incrementing integer field but just doesn't happen to be named "id", you can still have web2py use that field as the primary key by specifying the "id" field type:

db.define_table('legacy_table',
    Field('my_id', 'id'), ...)

However, if the primary key is not a single auto-incrementing integer field, you should instead look at the documentation on keyed tables. You can specify the primary key of the table, in which case, web2py will not create or expect an "id" field. However, there are some limitations in functionality.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top