如何在 Django REST API 中创建用户配置文件对象?

How to create user profile object in Django REST API?

我有两个用户配置文件模型,每个都指自定义用户

user/models.py

class Role(models.TextChoices):
    ONE = 'ON', 'One'
    TWO = 'TW', 'Two'


class ProfileOne(models.Model):
    user = models.OneToOneField('CustomUser', on_delete=models.CASCADE)


class ProfileTwo(models.Model):
    user = models.OneToOneField('CustomUser', on_delete=models.CASCADE)


PROFILE_MAP = {
    Role.ONE: ProfileOne,
    Role.TWO: ProfileTwo
}


class CustomUser(AbstractUser):
   # fields definition
   role = models.CharField(max_length=2, choices=Role.choices, null=True)

   objects = CustomUserManager()

   def create_profile(self, role):
        profile = PROFILE_MAP[role](user=self)
        profile.save()

        return profile

我需要在注册后为用户创建个人资料。我尝试在自定义用户管理器的 create_user() 方法中执行此操作,但没有效果。

user/managers.py

class CustomUserManager(BaseUserManager):
    def create_user(self, first_name, last_name, email, role, password, **extra_fields):
        # user initialization
        user.save()
        user.create_profile(role)

        return user

什么问题?经理适合这个吗?

我发现应该在适配器中执行此操作。

users/adapters.py

class CustomUserAccountAdapter(DefaultAccountAdapter):
    def save_user(self, request, user, form, commit=False):
        user = super().save_user(request, user, form, commit)
        data = form.cleaned_data
        user.role = data.get('role')
        user.save()
        user.create_profile(user.role)

        return user

project/settings.py

ACCOUNT_ADAPTER = 'users.adapters.CustomUserAccountAdapter'