DRF:сериализатор регистрации пользователей для прокси-моделей с вложенными сериализаторами

У меня есть модель User, которая наследуется от AbstractBaseUser, а также модель proxy, которая наследуется от модели User с расширенными полями и менеджером. Я хочу сериализовать и проверить модель User и модель proxy одновременно с помощью вложенных сериализаторов:

 ##manager for the user model
class CustomAccountManager(BaseUserManager):

    def create_superuser(self, email, firstname, lastname, password, **other_fields):
        ....

##user model
class User(AbstractBaseUser, PermissionsMixin):

    class TYPES(models.TextChoices):
         OWNER = "OWNER", "Owner"
         OTHERUSER = "OTHERUSER", "other user"
        ##user types

    base_type = TYPES.STUDENT

    type = models.CharField(
        _("User Type"), max_length=50, choices=TYPES.choices, default=base_type)
    email = models.EmailField(
        _("Your Email"), max_length=254, unique=True, blank=False, null=True)
    firstname = models.CharField(max_length=150, blank=False, null=True)
    lastname = models.CharField(max_length=150, blank=False, null=True)
    joined_date = models.DateTimeField(
        _("created date"), auto_now=True, auto_now_add=False)
    is_superuser = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=False)
    last_login = models.DateTimeField(
        _("last login"), auto_now=True, auto_now_add=False)

    objects = CustomAccountManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['firstname', 'lastname']

    def __str__(self):
        return self.firstname

# owner model manager
class OwnerManager(models.Manager):
    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, *kwargs).filter(type=User.TYPES.OWNER)

class OwnerMore(models.Model):
    user = models.OneToOneField(
        User, on_delete=models.CASCADE, blank=False, null=True)
        #extra fields dedicated to this user type


class Owner(User):
    base_type = User.TYPES.OWNER
    objects = OwnerManager()

    @property
    def extra(self):
        return self.OwnerMore

    class Meta:
        proxy = True

вот мой файл serializers.py:- он не работает должным образом, что-то не так с валидацией, я думаю.

class RegisterSerializerOwner(serializers.ModelSerializer):
    email = serializers.EmailField(
        required=True,
        validators=[UniqueValidator(queryset=User.objects.all())])

    password = serializers.CharField(
        write_only=True, required=True, validators=[validate_password])
    password2 = serializers.CharField(write_only=True, required=True)

    class Meta:
        model = User
        fields = ('email', 'firstname', 'lastname', 'password', 'password2',)
        extra_kwargs = {'password': {'write_only': True, },
                        'password2': {'write_only': True, }
                        }


class OwnerSerializer(serializers.ModelSerializer):
    user = RegisterSerializerOwner(many=False, read_only=False)

    class Meta:
        model = Owner
        fields = ('user', 'phone',)

    def validate(self, attrs):
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError(
                {"password": "Password fields didn't match."})

        return attrs

    def create(self, validated_data):
        users_data = validated_data.pop('user')
        owner = Owner.objects.create(**validated_data)
        for user_data in users_data:
            User.objects.create(question=owner, **user_data)

        return Owner
Вернуться на верх