django - 在 Django : User model inheritance or use UserProfile? 中扩展用户对象

标签 django django-users

要使用自定义字段扩展 User 对象,Django 文档建议使用 UserProfiles .然而,根据this大约一年前回答一个关于这个的问题:

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



以及this等文章阐述如何使用自定义字段扩展 User 模型,以及优点(直接从用户对象检索属性,而不是通过 .get_profile())。

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

最佳答案

我投票支持使用 用户文件 .

我使用了几个第三方应用程序。用户的外键将始终指向 auth.models.User。

示例:

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

以及您的自定义 User 模型:
class CustomUser(User):
    timezone = models.CharField(max_length=50, default='Europe/London')

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

如果通过 Article 实例访问 user 字段会发生什么?
这将引发异常:
u = a_article.user
u.timezone

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

也许这对您来说不是问题,并且您不想避免额外的数据库查询。
但我会使用 get_profile 方式。

2013 年 5 月更新

从 Django 1.5 开始,您可以 extend默认用户模型,或 substitute具有完全定制的模型。

2016 年 11 月更新

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

关于django - 在 Django : User model inheritance or use UserProfile? 中扩展用户对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2758137/

相关文章:

python - "django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 5: ' get_verbose_name ', expected ' 空 ' or ' endfor '. "

django - 从 ManyToMany 查询集中序列化数据

python - 获取 json 请求的 Django 问题

django - 为什么名字和姓氏字段没有保存在 django-registration 中?

django - 在 Django 中的 M2M 关系上使用 'through' 参数的原因

django - 尝试使用 Redis 队列在 heroku 上的 django 中进行一些异步处理

python - 强制 Django 使用 32 位 Python

django - 如何使用自定义 django 用户模型实现基于 Facebook AccountKit 的登录系统

Django 在外键中使用用户迁移模型失败

python - 将自定义操作添加到 UserModel 的管理页面