在Django中扩展用户对象:用户模型继承或使用UserProfile? [英] Extending User object in Django: User model inheritance or use UserProfile?

查看:156
本文介绍了在Django中扩展用户对象:用户模型继承或使用UserProfile?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要使用自定义字段扩展User对象,Django文档建议使用 UserProfiles 。但是,根据答案对于一年左右的一个问题:


扩展django.contrib.auth.models.User也可以更好地工作 - 自从Django的继承代码在模型API中重构之后。


和诸如这个展示了如何使用自定义字段扩展用户模型,以及优点(从用户对象直接获取属性,而不是通过.get_profile())。



所以我想知道在这个问题上是否有任何共识,还是使用一个或另一个的原因。或者甚至Django团队目前的想法?

解决方案

我投票使用 UserProfiles 。 >

我使用几个第三方应用程序。而用户的外键将永远指向auth.models.User。



示例:

 类文章(models.Model):
user = models.ForeignKey('auth.User')#而不是您的CustomUser
text = ....

您的自定义用户模型:

  class CustomUser(User):
timezone = models.CharField(max_length = 50,default ='Europe / London')

#使用UserManager获取create_user方法等
objects = UserManager()

如果您通过文章实例访问用户字段,会发生吗?
这将引发一个例外:

  u = a_article.user 
u.timezone

AttributeError:'User'对象没有属性'timezone'

也许这不是一个问题,你和你不要避免额外的数据库查询。
但我会使用get_profile方式。



2013年5月更新



自从Django 1.5以来,您可以 extend 默认用户模型,或替换完全定制的模式。



更新2016年11月



上述解决方案已过时,请参阅wim的评论


To extend the User object with custom fields, the Django docs recommend using UserProfiles. However, according to this answer to a question about this from a year or so back:

extending django.contrib.auth.models.User also works better now -- ever since the refactoring of Django's inheritance code in the models API.

And articles such as this lay out how to extend the User model with custom fields, together with the advantages (retrieving properties directly from the user object, rather than through the .get_profile()).

So I was wondering whether there is any consensus on this issue, or reasons to use one or the other. Or even what the Django team currently think?

解决方案

I vote for using UserProfiles.

I use several thrid party apps. And a foreign key to a User will always Point to auth.models.User.

Example:

class Article(models.Model):
    user = models.ForeignKey('auth.User') # instead of your CustomUser
    text = ....

And your custom User model:

class CustomUser(User):
    timezone = models.CharField(max_length=50, default='Europe/London')

    # Use UserManager to get the create_user method, etc.
    objects = UserManager()

What will be happen if you access the user field through an Article instance? This will raise an exception:

u = a_article.user
u.timezone

AttributeError: 'User' object has no attribute 'timezone'

Maybe this isn't a problem for you and you wan't to avoid the additional DB query. But i would use the get_profile way.

UPDATE May, 2013

Since Django 1.5 you can extend the default User model, or substitute with a completely customized model.

UPDATE Nov, 2016

The above solution is obsolete, see the comment from wim

这篇关于在Django中扩展用户对象:用户模型继承或使用UserProfile?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆