如何在Django 2.2中修复迁移模型的“ id”字段?

时间:2019-05-12 05:46:45

标签: python django django-models orm django-migrations

我有一个Django模型,其中不包含“ id”字段,但是在我以前迁移的MySQL实例中,出于某种原因,它显示了“ id”字段。我不断收到错误消息:

You are trying to add a non-nullable field 'id' to discussions without a default; we can't do that (the database n
eeds something to populate existing rows).

所以我去检查了我的models.py文件,该文件没有'id'字段:

class Discussions(models.Model):

    #team_id = models.ForeignKey(Teams, null=True, on_delete=models.CASCADE)
    login = models.CharField(max_length=30, null=True)
    uid = models.PositiveIntegerField(primary_key=True)
    title = models.CharField(max_length=30, null=True)
    body = models.CharField(max_length=500, null=True)
    comments = models.CharField(max_length=30, null=True)
    updated_at = models.CharField(max_length=21, null=True)

但是它显示在我的MySQL describe语句中:

+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| login      | varchar(30)  | YES  |     | NULL    |                |
| comments   | varchar(30)  | YES  |     | NULL    |                |
| updated_at | varchar(21)  | YES  |     | NULL    |                |
| body       | varchar(500) | YES  |     | NULL    |                |
| title      | varchar(30)  | YES  |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+

当我放下表格尝试重新同步数据库时,我收到一条错误消息:

django.db.utils.ProgrammingError: (1146, "Table 'my_project.app_discussions' doesn't exist")

理想情况下,我想以某种方式在视图中获取uid变量,以将其实际加载到表示id字段的数据库实例中。

        # tree->tuples->list of tuples
        json_tree = objectpath.Tree(data)
        login = tuple(json_tree.execute("$..login"))
        uid = tuple(json_tree.execute("$..id"))
        title = tuple(json_tree.execute("$..title"))
        body = tuple(json_tree.execute("$..body"))
        comments = tuple(json_tree.execute("$..comments_count"))
        updated_at = tuple(json_tree.execute("$..updated_at"))

        # took out `uid`
        parsed_list = list(zip(login, uid, title, body, comments, updated_at))

        # LOADING PHASE
        load_data = []

        # took out `u`
        for l, t, i, b, c, u in zip(login, uid, title, body, comments, updated_at):

            load_data.append(Discussions(l, t, i, b, c, u))

        Discussions.objects.bulk_create(load_data)

为什么我不能将此新模式迁移到MySQL?为什么我以前拥有过uid字段,但没有通过ORM将其映射到ID字段中?感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

id是主键,并且不能为空。 这样,您可以在先前的迁移中添加id字段为空,然后您需要更改以前的迁移,或者只是在模型中添加新字段并再次运行迁移

id = models.IntegerField(null=False, primary_key=True)