为什么用户模型继承不正常?

0 投票
1 回答
531 浏览
提问于 2025-04-15 19:21

我在我的Django应用中尝试使用User模型的继承。模型看起来是这样的:

from django.contrib.auth.models import User, UserManager

class MyUser(User):
    ICQ = models.CharField(max_length=9)
    objects = UserManager()

而身份验证后端看起来是这样的:

import sys

from django.db import models
from django.db.models import get_model
from django.conf import settings
from django.contrib.auth.models import User, UserManager
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import ImproperlyConfigured

class AuthBackend(ModelBackend):
    def authenticate(self, email=None, username=None, password=None):
        try:            
            if email:
                user = self.user_class.objects.get(email = email)
            else:
                user = self.user_class.objects.get(username = username)

            if user.check_password(password):
                return user

        except self.user_class.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            return self.user_class.objects.get(pk=user_id)
        except self.user_class.DoesNotExist:
            return None

    @property
    def user_class(self):
        if not hasattr(self, '_user_class'):
            self._user_class = get_model(*settings.CUSTOM_USER_MODEL.split('.', 2))
            if not self._user_class:
                raise ImproperlyConfigured('Could not get custom user model')
        return self._user_class

但是当我尝试进行身份验证时,在self.user_class.objects.get(username = username)这行代码上出现了一个“找不到匹配的MyUser查询”的错误。看起来在基础同步时创建的管理员用户(我使用的是sqlite3)存储在User模型中,而不是MyUser中(用户名和密码都是正确的)。或者说是其他什么问题吗?

我哪里做错了?这是一个来自http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/的例子。

1 个回答

4

和你提到的博客文章说的正好相反,在Django中,把这类数据存储在个人资料模型里仍然是推荐的做法。直接继承User会遇到各种问题,其中一个就是你现在碰到的:Django根本不知道你已经继承了User,它依然会在自己的代码中随意创建和读取User模型。其他你可能想用的第三方应用也是这样。

你可以看看这个链接,了解一下继承User背后的一些问题。

撰写回答