私の 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',
)
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 中に作成されませんよね...? では、なぜこの制約が作成されるのでしょうか... ?