【问题标题】:Problem with migrating my Database using Django使用 Django 迁移我的数据库的问题
【发布时间】:2021-07-01 04:31:37
【问题描述】:

我目前有一个使用 Heroku 的数据库,并希望将其迁移到 AWS,两者都使用 PostgresSQL。因此,在研究了如何完成之后,我按照this youtube video 上的步骤进行操作。

我最初在 Django 中使用我的 Heroku 数据库凭据运行 python manage.py dumpdata > dumpdata.json

之后,我将 settings.py 中的数据库凭证更改为 AWS 数据库凭证,然后运行 ​​python manage.py migrate --run-syncdb,它成功运行。

然后我运行代码python manage.py loaddata dumpdata.json,当我被抛出错误时。

出现以下错误:

django.db.utils.IntegrityError: Problem installing fixture 'C:\Users\Acer\Desktop\Web Development\Proffesional\eblossom\eblossom\eblossom\dumpdata.json': Could not load contenttypes.ContentType(pk=9): duplicate key value violates unique constraint "django_content_type_app_label_model_76bd3d3b_uniq"
DETAIL:  Key (app_label, model)=(user, profile) already exists.

我不明白这里出了什么问题,该站点一直运行良好,没有数据库编译错误,但是现在当我尝试将其迁移到 AWS 时,我遇到了这个问题。

以防万一我的models.py:

class Profile (models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    mobile_number = models.CharField(max_length=12, null=True)
    guest = models.BooleanField(default=False)

    def __str__(self):
        return f"{self.user}"

【问题讨论】:

  • 该错误意味着数据库中已经存在具有该主键的配置文件。在您运行 loaddata 之前,您的 AWS 数据库中是否已有配置文件用户?
  • 不,我的数据库不是空的
  • 忽略我之前的评论。该错误不是因为已经存在配置文件。这实际上是您转储 contenttype 表的问题,该表包含模型上的元数据。您应该在dumpdata 命令e.g: python manage.py dumpdata --exclude=contenttypes 中排除内容类型。类似话题here
  • 所以通过运行命令python manage.py dumpdata --exclude=contenttypes > dumpdata.json,我得到了一个小得多的文件,其中没有我的数据库内容......这有点令人担忧
  • 是的,文件会变小,因为您不再将 contenttypes 数据转储到 json 文件中。在contenttypes framework 上阅读此处。

标签: django database amazon-rds


【解决方案1】:

我总是在数据库、本地和远程、postgres 或 sqlite 之间这样做。

为了实现这一点,请按顺序执行以下步骤:

    # Start the same as you did on local database
    python manage.py dumpdata > db.json
    # push this file to your production/server location
    # and delete or start with a fresh new database
    python manage.py migrate
    python manage.py shell 
    # Enter the following in the shell
    from django.contrib.contenttypes.models import ContentType
    ContentType.objects.all().delete()
    # Exit shell and run following command
    python manage.py loaddata db.json

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-05
    • 2022-07-09
    • 2016-10-08
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2019-08-25
    相关资源
    最近更新 更多