简体   繁体   中英

How to fix Web2Py “<class 'sqlite3.IntegrityError'>(foreign key constraint failed)”?

I am attempting to add a new record into a database table that references another table and I am receiving this error from Web2Py: "(foreign key constraint failed)".

I am following the Web2Py books example as seen below:

Chapter 7: Forms and validators

Links to referencing records

Now consider the case of two tables linked by a reference field. For example:

 db.define_table('person', Field('name', requires=IS_NOT_EMPTY())) db.define_table('dog', Field('owner', 'reference person'), Field('name', requires=IS_NOT_EMPTY())) db.dog.owner.requires = IS_IN_DB(db, 'person.id', '%(name)s') 

A person has dogs, and each dog belongs to an owner, which is a person. The dog owner is required to reference a valid db.person.id by '%(name)s'.

This is where I am confused because I believe I am following the example unless I am really oblivious to my errors.

The model I am using is below.

I am attempting to create an album the requires an artist to exist, which the artist record does, from a form.

db.define_table('artist',
               Field('name', requires=(IS_SLUG(),
                                       IS_NOT_IN_DB(db, 'artist.name'))),
               auth.signature)

# IS_SLUG removes special chars, IS_NOT_IN_DB makes it unique
db.define_table('album',
               Field('name', requires=(IS_SLUG(),
                                       IS_NOT_IN_DB(db, 'album.name'))),
               Field('artist_id', 'reference artist'), ### HERE ###
               Field('album_art', 'upload'),
               Field('chapter', 'integer', requires=IS_NOT_EMPTY()),
               Field('act', 'integer', default=0),
               Field('release_date', 'date', requires=IS_NOT_EMPTY()),
               Field('num_of_tracks', 'integer', default=0),
               auth.signature)

db.album.artist_id.requires = IS_IN_DB(db, 'artist.id', '%(name)s')

I expected the form to insert the album, the same way that the artist form did.

I know the reference is causing the issue and I would really appreciate if anyone could help me see my errors.

The latest Firefox Developer Edition is having issues with Web2Py.

I switched to Chrome and everything works.

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