Django在'auth'应用中缺少迁移

时间:2018-08-21 23:10:55

标签: python django

我正在尝试在不同于通常的计算机上的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个迁移,但第十迁移不存在:

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中描述的推荐方法之一。这可能是问题的根源吗?

2 个答案:

答案 0 :(得分:1)

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

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

作为错误的解决方法,您可以在新计算机上进行迁移,这将创建新的用户模型迁移。找到文件名并在迁移文件lucy_web.0184_googlecredentials

中临时更改它

答案 1 :(得分:0)

我还使用了 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'

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