Django如何在多个配置文件中使用AUTH_PROFILE_MODULE?

2 投票
2 回答
1533 浏览
提问于 2025-04-16 11:30

假设我有不同的用户类型,比如员工、老师和学生,每种类型都有不同的资料:

我该怎么设置 AUTH_PROFILE_MODULE,才能通过 get_profile 获取到合适的用户资料呢?

2 个回答

0

使用UserProfile来处理多个用户资料可能会比较麻烦,因为它的设置比较简单。

我建议可以用UserProfile配合通用外键,或者干脆不使用UserProfile,直接创建独立的模型,并与用户建立外键关系。

如果你需要为这些额外的用户资料存储很多数据,最好把它们放在与UserProfile不同的模型中。我个人觉得UserProfile很容易变成一个杂乱无章的地方,存放那些没有合适归宿的用户数据。

不要因为你的数据听起来像是用户资料就觉得必须使用UserProfile。我认为UserProfile并不是为了处理所有问题而设计的。它只是为了弥补User模型的代码在django框架下,我们通常不去修改它来添加用户数据。

2

没有办法做到这一点,但你可以使用通用的键。

from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType

class UserProfileOne(models.Model):
    pass

class UserProfileTwo(models.Model):
    pass


class UserProfile(models.Model):
    content_type    = models.ForeignKey(ContentType)
    object_id       = models.PositiveIntegerField(db_index=True)
    content_object  = generic.GenericForeignKey('content_type', 'object_id')

举个例子:

UserProfile.objects.create(content_object=any_profile_instance)

User(pk=1).get_profile().content_object.some_special_field

如果你能提供更多信息,可能会找到更好的解决方案哦 :)

撰写回答