首页 > 解决方案 > 如何在 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...

标签: pythondjango

解决方案


是的,如果您使用 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


推荐阅读