【问题标题】:Django missing a migration in the 'auth' appDjango 在“auth”应用程序中缺少迁移
【发布时间】:2019-01-28 04:25:19
【问题描述】:

我正在尝试在与我通常使用的计算机不同的计算机上处​​理 Django 项目。但是,当尝试运行以下迁移时:

from django.conf import settings
import django.contrib.postgres.fields
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

    dependencies = [
        ('auth', '0010_auto_20180727_1345'),
        ('lucy_web', '0183_auto_20180814_1505'),
    ]

    operations = [
        migrations.CreateModel(
            name='GoogleCredentials',
            fields=[
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
                ('user', models.OneToOneField(limit_choices_to={'is_staff': True}, on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL)),
                ('token', models.CharField(max_length=255, null=True)),
                ('refresh_token', models.CharField(max_length=255, null=True)),
                ('token_uri', models.CharField(max_length=255, null=True)),
                ('client_id', models.CharField(max_length=255, null=True)),
                ('client_secret', models.CharField(max_length=255, null=True)),
                ('scopes', django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=255), null=True, size=None)),
            ],
            options={
                'abstract': False,
            },
        ),
    ]

我收到此错误消息:

django.db.migrations.exceptions.NodeNotFoundError:迁移 lucy_web.0184_googlecredentials 依赖项引用不存在的父节点('auth'、'0010_auto_20180727_1345')

跟随https://groups.google.com/forum/#!topic/django-users/m59NufO1GI8,进入django/contrib/auth/migrations目录,发现确实有9个migration,但是第10个migration却没有:

Kurts-MacBook-Pro:auth kurtpeek$ ls migrations
0001_initial.py
0002_alter_permission_name_max_length.py
0003_alter_user_email_max_length.py
0004_alter_user_username_opts.py
0005_alter_user_last_login_null.py
0006_require_contenttypes_0002.py
0007_alter_validators_add_error_messages.py
0008_alter_user_username_max_length.py
0009_alter_user_last_name_max_length.py
__init__.py
__pycache__/
Kurts-MacBook-Pro:auth kurtpeek$ pwd
/Users/kurtpeek/.local/share/virtualenvs/lucy-web-oCa8O1zi/lib/python3.7/site-packages/django/contrib/auth

问题是,我还没有将虚拟环境检查到版本控制中,并且我目前无法访问另一台计算机。不过,我也觉得我不应该检查项目的 Django 源代码。

我的问题是:这种情况是如何发生的?我怀疑它与项目中自定义django.contrib.auth.User 模型的方式有关。我们有一个lucy_web/models/user.py,其内容类似于以下内容:

from django.contrib.auth.models import User
from django.contrib.auth.signals import user_logged_in, user_logged_out, user_login_failed
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from auditlog.registry import auditlog
from lucy_web.models import LucyGuide
from crequest.middleware import CrequestMiddleware
from lucy_web.lib import intercom

# overrides built in user to provide reasonable unique constraints
User._meta.get_field('username')._unique = True
# TODO(kayla): fix this, the unique constraint on email doesn't seem to be working in prod
# I suspect the username unique constraint only works because it's the default setting
User._meta.get_field('email')._unique = True


auditlog.register(User)


@property
def family(self):
    if hasattr(self, 'employee_family'):
        return self.employee_family
    elif hasattr(self, 'partner_family'):
        return self.partner_family
    else:
        return None


@property
def is_employee(self):
    return hasattr(self, 'employee_family')


@property
def user_apn(self):
    return self.userapn_set.order_by("created_at").last()


@property
def lucy_guide(self):
    try:
        return self.lucyguide
    except LucyGuide.DoesNotExist:
        return None


def user__str__(self):
    """
    User model's __str__ method.
    We use a different name than '__str__' because dunder names
    are reserved by Python and subject to breakage without warning
    (cf. https://www.python.org/dev/peps/pep-0562/#backwards-compatibility-and-impact-on-performance).
    """
    return f"{self.first_name} {self.last_name}".strip()


@property
def profile(self):
    if hasattr(self, 'user_profile'):
        return self.user_profile
    else:
        return None


@property
def using_app(self):
    if hasattr(self, 'user_profile'):
        return self.user_profile.using_app

    return False


@property
def activation_code(self):
    if hasattr(self, 'user_profile'):
        return self.user_profile.activation_code

    return False


User.add_to_class('family', family)
User.add_to_class('is_employee', is_employee)
User.add_to_class('user_apn', user_apn)
User.add_to_class('lucy_guide', lucy_guide)
User.add_to_class('__str__', user__str__)
User.add_to_class('profile', profile)
User.add_to_class('using_app', using_app)

简而言之,我们使用add_to_class 方法将属性添加到Django 的User 模型中。这似乎不是https://docs.djangoproject.com/en/2.1/topics/auth/customizing/#extending-user 中描述的推荐方法之一。这可能是问题的根源吗?

【问题讨论】:

    标签: python django


    【解决方案1】:

    如果您将add_to_class 用于 Django User 模型,它将检测外部包中的更改并在外部包迁移目录中应用迁移(通常在您的虚拟环境中)。

    如果需要 User 模型来创建以后的迁移,它将在顶部提供的迁移文件 (lucy_web.0184_googlecredentials) 中引用。选择的用户迁移编号是创建时最后可用的,以确保兼容性。

    作为一种不好的解决方法,您可以在新计算机上进行迁移,这应该会创建新的用户模型模型迁移。在迁移文件lucy_web.0184_googlecredentials中找到文件名并临时改一下

    【讨论】:

    • 那么您是否同意不推荐使用add_to_class 来扩展用户模型?它似乎不是任何地方都没有记录的“内部”功能。可能更好的方法是使用代理模型?
    • 根据您的情况,有几种方法可以完成: - 如果不需要更改数据库,则使用代理模型 - 与单独模型的 OneToOne 关系 - 子类化和覆盖模型 讨论了其中一些方法关于docs.djangoproject.com/en/2.1/topics/auth/customizing/…
    【解决方案2】:

    我还使用了add_to_class() 并在同一环境中创建了新项目。 它需要删除环境中子文件夹“迁移”中的所有迁移和 *.pyc。只留下__init__.py 文件。

    ...\Envs\blah-blah-env\Lib\site-packages\django\contrib\...
    

    例如路径(其中之一):

    c:\Users\user\Envs\blah-blah-env\Lib\site-packages\django\contrib\auth\migrations\
    

    如果你得到了(source):

    django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency account.0001_initial on database 'default'
    

    删除数据库或清除迁移表,删除项目中的迁移文件。祝你好运!

    【讨论】:

      猜你喜欢
      • 2016-05-22
      • 1970-01-01
      • 2016-09-05
      • 2016-04-14
      • 1970-01-01
      • 2020-07-03
      • 1970-01-01
      • 2012-02-17
      • 1970-01-01
      相关资源
      最近更新 更多