IntegrityError when adding null value to foreign key using web2py
I am receiving an IntegrityError from web2py when trying to insert a record into a table named Foods. The table has a foreign key to Recipes, but I would like to add a row without a recipe_id.
<class 'gluon.contrib.pymysql.err.IntegrityError'>((1452, u'Cannot add or update a child row: a foreign key constraint fails (`pymeals`.`foods`, CONSTRAINT `foods_ibfk_1` FOREIGN KEY (`recipe_id`) REFERENCES `recipes` (`id`) ON DELETE CASCADE)'))
This is my table
+-----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
| recipe_id | int(11) | YES | MUL | NULL |开发者_运维技巧 |
+-----------+--------------+------+-----+---------+----------------+
I have defined the table in web2py using the following code:
db.define_table('foods',
Field('name'),
Field('recipe_id', db.recipes, required=False, notnull=False, requires=None))
I believe the problem I am having lies with web2py as I can insert into the Foods table directly from the mysql command line prompt without specifying a recipe_id.
Am I missing something here? I'm new to MySQL and web2py :(
Make sure your Foods and Recipes have same engines. If you have different engines, then this problem will be occured.
Eg: Foods (MyISAM) and Recipes (InnoDB) will give error.
精彩评论