gpt4 book ai didi

python - Django 1.8+ 扩展用户模型

转载 作者:行者123 更新时间:2023-11-30 22:48:29 25 4
gpt4 key购买 nike

我知道这个问题已被问过数百次,但其中大多数包含已接受的答案,但这些答案不再有效。其中一些适用于 Django 1.5,其中一些甚至更旧。

所以我正在寻找最新的答案。最类似于我的问题的问题是 this one .

我正在使用 django-registration 模块,并且我希望用户拥有其他字段(例如整数 user.points)。我可以实现自己的 MyUser 模型并相应地更改程序的其余部分。但是我怀疑这是否符合注册模块的要求。因此,我想理想的方法是继续使用 User 模型,并以某种方式将它们联系起来,以便每当创建 User 对象时,都会有一个相应的 MyUser > 使用其他字段的默认值创建对象。

-如何使用 Django 1.8+ 执行此操作?

感谢您的帮助,

最佳答案

有关该主题的文章:How to Extend Django User Model

我使用的是一对一方法:

class UserProfile(models.Model):
user = models.OneToOneField(User, related_name="profile")
#more fields

@staticmethod
@receiver(post_save, sender=User, dispatch_uid="at_user_post_save")
def user_post_save(sender, instance, **kwargs):
#create new profile on user.save() (if necessary)
profile, new = UserProfile.objects.get_or_create(user=instance)


#in view
profile = request.user.profile

更新:

Are there any other caveats? Like what happens when I remove a UserProfile?

UserProfile 是持有该关系的人,因此删除时不应删除任何用户。您可以通过 on_delete 控制用户被删除时必须采取的行为夸格。

Also do they always have the same private keys?

并不是每个类都有自己的 PK,只是 UserProfile 将 PK 保存到其用户

OneToOneField 从概念上讲是一个带有 unique=TrueForeignKey,最大的区别是关系的反面不返回包含 0/1 元素的列表,但如果 null=True,则元素本身或引发 DoesNotExistNone

我唯一不喜欢这种方法的是,您总是必须再执行 1 次查询才能获取 user.profile。当从 auth 获取新的 user 时,我仍然找不到一种良好且干净的方法来始终 .select_lated('profile') ,但这更多是身份验证系统的问题,而不是方法本身的问题。

关于python - Django 1.8+ 扩展用户模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40153280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com