Django自定义用户添加第二个用户模型

时间:2013-12-25 23:19:18

标签: python django django-models

我目前正在使用Django 1.5自定义用户模型。使用下面的代码,如何添加新的第二类用户?

我想添加一个名为StandardUser的新用户我已经有CompanyUser类型,即

class StandardUser(AbstractEmailUser):
    class Meta:
        app_label = 'accounts'

但这似乎不起作用,我怎样才能实现这个目标?

以下当前代码:

class AbstractEmailUser(AbstractBaseUser, PermissionsMixin):
    """
    Abstract User with the same behaviour as Django's default User but
    without a username field. Uses email as the USERNAME_FIELD for
    authentication.

    Use this if you need to extend EmailUser.

    Inherits from both the AbstractBaseUser and PermissionMixin.

    The following attributes are inherited from the superclasses:
        * password
        * last_login
        * is_superuser
    """
    email = models.EmailField(_('email address'), max_length=255,
                              unique=True, db_index=True)
    is_staff = models.BooleanField(_('staff status'), default=False,
        help_text=_('Designates whether the user can log into this admin '
                    'site.'))
    is_active = models.BooleanField(_('active'), default=True,
        help_text=_('Designates whether this user should be treated as '
                    'active. Unselect this instead of deleting accounts.'))
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    objects = EmailUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    class Meta:
        abstract = True

class CompanyUser(AbstractEmailUser):
    company = models.CharField(max_length=100)

    class Meta:
        app_label = 'accounts'

1 个答案:

答案 0 :(得分:1)

你只能拥有一个官方'项目中的用户模型:
https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#substituting-a-custom-user-model

我建议你这样组织:

class StandardUser(AbstractEmailUser):
    class Meta:
        app_label = 'accounts'

class CompanyUser(StandardUser):
    company = models.CharField(max_length=100)

    class Meta:
        app_label = 'accounts'

和settings.py

AUTH_USER_MODEL = 'myapp.StandardUser'

换句话说,根据Django模型继承,每个CompanyUser都通过自动StandardUser关联OneToOneField

这种方法类似于Object composition,我认为它可能是唯一可以在Django中运行的方法。

这意味着,为了查询非公司用户,您必须执行以下操作:

StandardUser.objects.filter(companyuser=None)

(您可能需要custom queryset manager来支持此

如果你走这条路,可能不再需要AbstractEmailUser类,你可以重命名它,并使它成为具体的StandardUser类。