django 中的迁移命令在部署到 heroku 时出错

Migrate command in django giving error when deployed to heroku

所以我尝试将 django 应用程序部署到 heroku,它在本地运行良好。

虽然部署过程成功完成,但迁移命令出错。

django.db.migrations.exceptions.NodeNotFoundError: Migration accounts.0001_initial dependencies reference nonexistent parent node ('auth', '0013_alter_user_email')

这是我的迁移文件;

import accounts.models
from django.conf import settings
import django.contrib.gis.db.models.fields
from django.db import migrations, models
import django.db.models.deletion
from django.contrib.postgres.operations import CreateExtension


class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('auth', '0013_alter_user_email'),
    ]

    operations = [...]

从评论中的讨论来看,迁移 0013_alter_user_email 似乎实际上并不存在于 auth 应用程序中。生成它是因为我通过在运行时使用 User._meta.get_field('email').unique 访问它来修改用户模型以使电子邮件字段唯一。

您正在 运行 修改用户模型,导致为其生成迁移。这种做事方式被称为 monkey patching,这是一种 不好的做法 django.contrib.auth 可以说是第 3 方应用程序,像这样修改它可能会产生不利影响,其中之一是您目前正在经历的。发生的事情是你修改了用户模型,它在 Django 包中本地生成了一个迁移。由于这是一个包,它不是您代码的一部分,而是单独安装的。你甚至不能在 Heroku 上 运行 makemigrations 来解决这个问题(无论如何都不是推荐的解决方案),因为 Heroku 上的任何文件系统更改都是临时的,并且会在 dyno 加载时被删除。

Django 允许 customize authentication [Django docs] / user model very easily. In general as a best practice in Django one should always use a custom user model when starting a project.

您的解决方案是删除所有迁移,删除数据库,重新安装 Django 以确保它干净且未修改,并使用如上所述的自定义用户模型:

from django.contrib.auth.models import AbstractUser
from django.utils.translation import gettext_lazy as _


class User(AbstractUser):
    email = models.EmailField(_('email address'), blank=True, unique=True)

在设置中将其设置为AUTH_USER_MODEL [Django dosc]。还需要进行其他更改,例如为管理站点注册模型、更改 ModelAdmin(即 UserAdmin)中的某些表单以及查看和重构您的代码。