修改django数据库时提示重命名表主键, Did you rename house.houseid to house.id (a BigAutoField)? [y/N] n

一,问题描述

 在django中models.py文件里新增一个order表,通过“py manage.py makemigrations”命令做迁移时,发现小黑框出现让我重命名数据库里已经存在的表的id,提示添加一个非空‘id’到一个早已存在的house表是不允许的;具体提示如下:

二,解决问题

尝试了如下解决方法:

1,注释掉models.py中新增的order表的代码重新执行“py manage.py makemigrations”,发现仍然提示上述错误。

2,stackoverflow里有人碰到过类似情况(具体链接点此处),回复的解决方案如下:

This might sound dumb but did you perhaps run a find and replace in your project where you replaced id with pid? Django automatically generates primary key fields with the name id not pid. This or perhaps previously you ran a modified version of Django which generated fields named pid instead of id is what I can think happened. As below comment states just edit your migration files and correct them.

 大意是说这问题挺离谱的,有可能在在models里自定义的主键是id,但是在代码里用的是pid,才产生这问题;

经过排查代码发现,有个带参接口用的是“houseid”,而非models.py中自定义的主键“id”,把“houseid”换成“id”后,运行“py manage.py makemigrations”发现无报错了。

 1 views.py
 2 
 3 def addToHouseOrder(request, houseid):
 4     """
 5     用户加入房子到订单列表
 6     :param request:
 7     :param id: houseid
 8     :return:
 9     """
10     if request.method == "GET":
11         currentUser = request.session['username']
12         print(currentUser, houseid)
13         houseResult = House.objects.filter(id=houseid)
14         return HttpResponse(houseid)
15     elif request.method == "POST":
16         pass

 

posted @ 2021-12-09 10:01  puppet洛洛  阅读(226)  评论(0编辑  收藏  举报