Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 未在数据库中创建外键字段_Mysql_Django_Foreign Keys_Django Rest Framework - Fatal编程技术网

Mysql 未在数据库中创建外键字段

Mysql 未在数据库中创建外键字段,mysql,django,foreign-keys,django-rest-framework,Mysql,Django,Foreign Keys,Django Rest Framework,我试图将注释与用户模型相关联,但不知何故,该字段没有在数据库中创建。当我尝试访问该页面时,显示以下错误: 1054,“字段列表”中的未知列“用户注释.用户id” 这些在models.py中: 如果我将用户变量命名为user_id,则在管理面板中创建新注释时,将显示一个错误,说明找不到user_id **更新** 我删除了整个数据库,删除了db_表选项,从而创建了user_id。但现在,在创建新评论时,以下内容: IntegrityError at /admin/api/comment/add/

我试图将注释与用户模型相关联,但不知何故,该字段没有在数据库中创建。当我尝试访问该页面时,显示以下错误:

1054,“字段列表”中的未知列“用户注释.用户id”

这些在models.py中:

如果我将用户变量命名为user_id,则在管理面板中创建新注释时,将显示一个错误,说明找不到user_id

**更新**

我删除了整个数据库,删除了db_表选项,从而创建了user_id。但现在,在创建新评论时,以下内容:

IntegrityError at /admin/api/comment/add/
(1452, 'Cannot add or update a child row: a foreign key constraint fails (`softwarestore`.`api_comment`, CONSTRAINT `api_comment_user_id_14315666_fk_api_user_id` FOREIGN KEY (`user_id`) REFERENCES `api_user` (`id`))')
 user = models.ForeignKey('auth.User', related_name='comments', on_delete=models.CASCADE)

您是否尝试过简单地替换以下内容:

IntegrityError at /admin/api/comment/add/
(1452, 'Cannot add or update a child row: a foreign key constraint fails (`softwarestore`.`api_comment`, CONSTRAINT `api_comment_user_id_14315666_fk_api_user_id` FOREIGN KEY (`user_id`) REFERENCES `api_user` (`id`))')
 user = models.ForeignKey('auth.User', related_name='comments', on_delete=models.CASCADE)


然后运行makemigrations?

是的,刚刚做了,但仍然没有区别。您可以运行python manage.py makemigrations或删除migrations文件夹并重新启动吗?奇怪。同样的事情。但是在运行makemigrations时,我读取了-Add field user to comment。我删除了数据库,删除了Meta中的db_table选项,并将user更改为auth.user,在再次运行所有操作后,它工作正常,创建了一个user_id。现在,在保存新注释时,我收到一个IntegrityError,说外键约束失败。我认为您在序列化程序中也使用了id。id在创建新对象时自动递增。您在编写API时是否将其放入序列化程序?您是否运行makemigrations和migrate?是的,我运行了。请检查我对答案的评论。