django如何使用AUTH_PROFILE_MODULE多个配置文件?

时间:2011-02-09 03:50:46

标签: python django django-models

假设我有不同的用户类型的配置文件 - 员工,老师,学生:

如何指定AUTH_PROFILE_MODULE以便使用get_profile取回相应的个人资料?

2 个答案:

答案 0 :(得分: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

如果您可以提供更多信息,那么何时可以找到更好的解决方案:)

答案 1 :(得分:0)

尝试使用UserProfile的简单配置来使用多个配置文件可能会更麻烦。

我建议将UserProfile与通用外键一起使用,或者完全抛弃UserProfile并使用User外键创建单独的模型。

如果您要将大量数据附加到这些额外的用户配置文件,我会将它们保存在与UserProfile分开的模型中。我对UserProfile的个人看法是它很快就会成为没有好家的用户数据的倾销场所。

不要因为您的数据听起来像是个人资料信息而认为您必须使用UserProfile。我不认为UserProfile曾经打算解决所有问题。我认为这是一种弥补用户模型的代码在django代码下的一种方式,我们通常不会用它来添加用户数据。