Django自定义用户迁移会破坏syncdb

时间:2014-10-08 08:43:51

标签: python django migration django-south django-custom-user

在我的django项目中,我从一开始就将django auth用户换成了自定义用户模型。我为用户使用proxymodel作为AUTH_USER_MODEL。 项目布局有点像,

manage.py
project/
    __init__.py
    settings.py
    urls.py
    wsgi.py
userlocal/
    models.py
userproxy/
    models.py

如果相关部分如下,

项目/ settings.py

AUTH_USER_MODEL = 'userproxy.ProxyUser'

INSTALLED_APPS = (
    'south',

    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
    'django.contrib.admindocs',

    'project',
    'userlocal',
    'userproxy',
)

userlocal / models.py

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin


class LocalUser(AbstractBaseUser, PermissionsMixin):
    """
    Custom User Model
    """

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    username = models.CharField(max_length=255, unique=True)
    email = models.CharField(max_length=255, unique=True)

    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_deleted = models.BooleanField(default=False)
    is_registered = models.BooleanField(default=True)

的userProxy / models.py

from userlocal.models import LocalUser


class ProxyUser(LocalUser):

    class Meta():
        proxy = True

到目前为止,syncdb工作正常。现在我想对我的userlocal模型进行更改,以便创建初始模式迁移。

python manage.py schememigration --initial userlocal

 + Added model userlocal.LocalUser
 + Added M2M table for groups on userlocal.LocalUser
 + Added M2M table for user_permissions on userlocal.LocalUser
Created 0001_initial.py ...

我将以下内容添加到我的userlocal模型中,

first_name = models.CharField(max_length=255, null=True)
last_name = models.CharField(max_length=255, null=True)

为它创建一个新的迁移,

python manage.py schemamigration --auto userlocal

 + Added field first_name on userlocal.LocalUser
 + Added field last_name on userlocal.LocalUser
Created 0002_auto__...py. ...

现在,当我运行syncdb时,它存在于一个OperationalError

Syncing...
Creating tables ...
Creating table south_migrationhistory
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table django_content_type
Creating table django_session
Creating table django_site
Creating table django_admin_log
Creating table userlocal_localuser
Traceback (most recent call last)
...
...
...
django.db.utils.OperationalError:
(1005, "Can't create table 'project_dev.#sql-11e1_10e' (errno: 150)")

当我调试syncdb进程时,执行的最后一个查询是

Creating table userlocal_localuser
ALTER TABLE `django_admin_log`
ADD CONSTRAINT `user_id_refs_id_7b1a6083`
FOREIGN KEY (`user_id`)
REFERENCES `userlocal_localuser` (`id`);

因此它尝试从django_admin_log到userlocal_localuser创建约束。但后者不是在syncdb期间创建的,因为它有迁移,对吧......?那么为什么要创建这个约束......?

0 个答案:

没有答案