用户模型mixin与Django

时间:2019-02-19 16:06:49

标签: django mixins

我正在Django中创建自定义User模型。我的模型已经有一个基类,现在我使用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应该是我创建的几乎所有模型的基类。在这种情况下,我尝试从AbstractBaseUserModelMixin继承:

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迁移:

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_datelast_update字段不存在。用这种方式做错什么了?

1 个答案:

答案 0 :(得分:2)

您正在使用from django.db.models import Manager as DjangoModel,而不是django.db.models import Model as DjangoModel。 由于字段未在Model的子类上定义,因此Django不会将其视为有效字段。