在我的 django 项目中,我从一开始就将 django auth 用户换成了自定义用户模型。我为用户使用代理模型作为 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',
)
用户本地/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)
用户代理/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. ...
现在,当我运行同步数据库时,它存在于 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期间创建的,因为它有迁移,对吧......?那么为什么要创建这个约束......?