简体   繁体   中英

How can I define a custom primary key in web2py

I'm building a simple application in web2py which will be used to store some data in tables using a web based form.

The following code is an example of a table related to a drop down menu.

#########################################################################
## Conglomerado_tenencia_opcion
db.define_table('Conglomerado_tenencia_opcion',
            Field('num_tenencia','integer', required='TRUE'),
            Field('nombre_tenencia', 'text', required='TRUE'))

if db(db.Conglomerado_tenencia_opcion.id>0).count() == 0:
db.Conglomerado_tenencia_opcion.insert(num_tenencia='1',nombre_tenencia='Ejidal')
db.Conglomerado_tenencia_opcion.insert(num_tenencia='2',nombre_tenencia='Comunal')
db.Conglomerado_tenencia_opcion.insert(num_tenencia='3',nombre_tenencia='Propiedad particular')
db.Conglomerado_tenencia_opcion.insert(num_tenencia='4',nombre_tenencia='Propiedad federal')

However this application will be passed around several collegues and thus autogenerated IDs may represent a problem when trying to gather all the information they will individually collect.

I would like to declare as primary key the field 'num_tenencia' but apparently web2py doesn't allow it, as the primary key must be autogenerated. As you can see in the code above, 'num_tenencia' is unique to every record.

¿Does anyone know a solution to this?

You can do:

db.define_table('Conglomerado_tenencia_opcion',
    Field('num_tenencia','integer', required=True),
    Field('nombre_tenencia', 'text', required=True),
    primarykey=['num_tenencia'])

However, this is not recommended, as it limits some of the web2py functionality (for more details, see the book section on keyed tables ).

In any case, even if you set your own primary key, if different versions of the app will be running on different systems, you will still have to come up with a scheme to ensure there are no duplicates across systems (perhaps uuid's).

As an alternative, you might be better off creating a workflow to combine data from the separate databases. In fact, the web2py documentation provides a recipe for just such a workflow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM