在Django中扩展用户模型

3

http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/

在扩展用户模型方面,上述文章列出了两种方法:旧方法(使用ForeignKey)和新方法(使用继承的User模型)。但同时,该文章的发布日期为2008年8月。

我正在使用Django的开发版本。

您会推荐使用继承方式扩展Django User模型还是使用ForeignKey方法?

我在几篇帖子中读到,不建议扩展django.contrib.auth.models.User,所以我不会考虑那种方法。

3个回答

1

Dominique Guardiola是正确的。使用AUTH_PROFILE_MODEL。James Bennett在他的“Django深入”演讲中重申了这一点。http://www.youtube.com/watch?v=t_ziKY1ayCo&feature=related 大约在1小时37分钟左右。

  • 决定我们想要放置用户个人资料的应用程序,让我们称之为BngGangOfFour。
  • 定义一个模型类,为了清晰起见,我们将其命名为UserProfile,并赋予它我们所需的额外字段。

BngGangOfFour/models.py

from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User) #notice it must contain a 1 to 1 field with the auth user.
    last_ip_address = models.CharField(max_length=20, default="")
  • 编辑settings.py文件,将我们新创建的模型指定为用户配置文件。

settings.py

....
AUTH_PROFILE_MODULE = 'BngGangOfFour.UserProfile' #not case sensitive.
....
  • 直接从用户对象中访问个人资料。

BngGangOfFour/views.py

....
def index(request):
    if request.user.get_profile().last_ip_address = "127.0.0.1":
        print("why hello me!")    
    return render_to_response('index.html', locals(), context_instance=RequestContext(request))

喝一杯冰啤酒,结束这一天的工作。

1
据我所知,更清晰的方法——如果这适合于您的项目架构——是拥有一个独立的用户配置文件模型,并使用AUTH_PROFILE_MODEL设置将其链接到Django用户模型。
请参阅Django文档关于存储用户附加信息

0
唯一可以通过继承干净地扩展User的时间是,如果您正在编写一个身份验证后端,该后端将返回适当模型的实例。

本文描述了如何编写一个认证后端来返回用户实例。我只是发布这个问题,以便更好地了解哪种方法更好。我确实有一个先入为主的观念,即“新方法”=更好。 - Rami_H

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接