用户模型与 django 混合
User model mixin with django
我正在 Django 中创建自定义 User
模型。我的模型已经有了一个基础 class,现在我使用 mixin 将其分开:
from django.db.models import Manager as DjangoModel
class ModelMixin(DjangoModel):
class Meta:
abstract = True
objects = Manager() # Not relevant
creation_date = DateTimeField(auto_now_add=True,
help_text=_('The date in which the database entry was created'),
verbose_name=_('Creation date'))
last_update = DateTimeField(auto_now=True,
help_text=_('The last time that the database entry was updated'),
verbose_name=_('Last update'))
class Model(ModelMixin):
class Meta(ModelMixin.Meta):
abstract = True
Model
应该是我创建的几乎所有模型的基础 class。在这种情况下,我试图继承 AbstractBaseUser
和 ModelMixin
:
class User(AbstractBaseUser, ModelMixin):
objects = UserManager()
EMAIL_FIELD = 'email'
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
email = EmailField(unique=True,
help_text=_('Email address'),
error_messages={
'unique': _('This email address is already registered.')
}
)
is_active = BooleanField(
default=False,
help_text=_('Whether the user is active')
)
但是,mixin 迁移没有被应用,正如我所看到的描述数据库上的table:
CREATE TABLE IF NOT EXISTS "futils_user" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "password" varchar(128) NOT NULL, "last_login" datetime NULL, "email" varchar(254) NOT NULL UNIQUE, "is_active" bool NOT NULL);
请注意 creation_date
和 last_update
字段不存在。这样做有什么问题吗?
您正在使用 from django.db.models import Manager as DjangoModel
而不是 django.db.models import Model as DjangoModel
。
由于字段未在 Model
的子类上定义,Django 不会将它们作为有效字段。
我正在 Django 中创建自定义 User
模型。我的模型已经有了一个基础 class,现在我使用 mixin 将其分开:
from django.db.models import Manager as DjangoModel
class ModelMixin(DjangoModel):
class Meta:
abstract = True
objects = Manager() # Not relevant
creation_date = DateTimeField(auto_now_add=True,
help_text=_('The date in which the database entry was created'),
verbose_name=_('Creation date'))
last_update = DateTimeField(auto_now=True,
help_text=_('The last time that the database entry was updated'),
verbose_name=_('Last update'))
class Model(ModelMixin):
class Meta(ModelMixin.Meta):
abstract = True
Model
应该是我创建的几乎所有模型的基础 class。在这种情况下,我试图继承 AbstractBaseUser
和 ModelMixin
:
class User(AbstractBaseUser, ModelMixin):
objects = UserManager()
EMAIL_FIELD = 'email'
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
email = EmailField(unique=True,
help_text=_('Email address'),
error_messages={
'unique': _('This email address is already registered.')
}
)
is_active = BooleanField(
default=False,
help_text=_('Whether the user is active')
)
但是,mixin 迁移没有被应用,正如我所看到的描述数据库上的table:
CREATE TABLE IF NOT EXISTS "futils_user" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "password" varchar(128) NOT NULL, "last_login" datetime NULL, "email" varchar(254) NOT NULL UNIQUE, "is_active" bool NOT NULL);
请注意 creation_date
和 last_update
字段不存在。这样做有什么问题吗?
您正在使用 from django.db.models import Manager as DjangoModel
而不是 django.db.models import Model as DjangoModel
。
由于字段未在 Model
的子类上定义,Django 不会将它们作为有效字段。