python - 如何在 Django 中创建扩展的用户对象?
问题描述
I created a model ExtendedUser
to extend the User
Django built-in model class using the approach described in the official documentation:
https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#extending-the-existing-user-model
so that I can benefit from the existing authentication features provided by Django.
That works all fine however I wonder now, whenever I want to create a new ExtendedUser
, that means for every ExtendedUser
, I also need to create an original User
to fullfill the one-to-one relationship?
Or what else does it mean the following:
Assuming an existing Employee Fred Smith who has both a User and Employee model, you can access the related information using Django’s standard related model conventions[...]
In a script to create objects, would this mean the following:
u1 = User.objects.create_user(username="u_1", email="u_1@abc.com", password="pw_u_1")
ext_u_1 = ExtendedUser.objects.create(id=u1.id, user=u1, prop_1="XYZ")
where
class ExtendedUser(models.Model):
user = models.OneToOneField(User, ...)
# More properties...
解决方案
是的,如果您使用 OneToOne 字段进行扩展,则需要创建两个对象,即 User 以及 ExtendedUser 来实现一对一的关系。
但我建议不要使用 OneToOne 字段,而是覆盖 Django 提供的 AbstractUser 模型来创建 ExtendedUserModel,即使您现在不需要 ExtendedUserModel 中的任何额外内容。它将帮助您将来轻松地将任何新字段、方法添加到您的用户模型中,并且您不需要为单个用户创建两个对象。
Django 文档中也提出了相同的建议。参考:- https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project
推荐阅读
- web-scraping - 如何使用 scrapy 抓取任何网站,以使网站不会将我的机器人视为注册或登录用户?
- android - Kotlin 使用 getter 作为只读变量
- mongodb - 以微服务精神从本地服务器连接到本地 Mongodb Docker 容器
- php - 将值设置为发布变量 $this->input->post codeigniter
- c - 在 x11 中命名一个新窗口
- mongodb - 将 google 电子邮件 ID 与数据库中的电子邮件 ID 进行比较并返回用户详细信息
- python-3.x - 隐式定义生成器的产量?
- matlab - 如何将 Maple 代码重写为 Matlab,函数 fsolve() 和 solve()?
- python - 查找类似文档
- elasticsearch-5 - Elasticsearch - 有没有一种方法可以将地理边界框与距离相结合