【问题标题】:Django change model, migrate, and update the existing recordsDjango 更改模型、迁移和更新现有记录
【发布时间】:2021-08-25 08:28:31
【问题描述】:

我有一个 Django 模型定义为:

from users.models import User

class Record(models.Model):
  user = models.ForeignKey(
            User,
            on_delete=SET_NULL,
            null=True)
  ...

我意识到最好将上面的模型重写为:

from userprofile.models import UserProfile

class Record(models.Model):
  user = models.ForeignKey(
            UserProfile,
            on_delete=SET_NULL,
            null=True)
  ....

如何迁移(因此使用模型Record 的新定义),而不必丢失数据库中的旧Record 实例?这种迁移的一般过程是什么?因为如果我使用Record 的新定义进行迁移,我将无法访问旧的Record 对象,因此我无法更新它们。但是,如果我不迁移,Django 不会让我使用UserProfile 作为user 字段。

【问题讨论】:

    标签: django django-models django-migrations


    【解决方案1】:

    没有什么可以通过这种方式迁移,因为user 是一个 Python 属性,并且没有支持 db 列,因为它没有定义为 ForeignKey。

    在这种情况下,Django 会自动处理这个问题,因为它会发现模型名称的变化,它会改变 DB 端的表名,然后它会更新 Record 表的引用表。

    您可以运行 python manage.py makemigrations 并查看生成的迁移。

    【讨论】:

    • 抱歉,我的问题过于简单化了。它确实是一个外键。我已经更新了问题。
    猜你喜欢
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多