How to use a single serializer to save multiple models

Problem : I’m unable to save the both models in database from a single serialzer.

Description : I’m using djoser auth library for registration and authentication. for that i’m using custom django auth user and mapped it with userprofile model.
Since i’m using userprofile along with the django user, i have to use custom register serializer.

# My Models
class CustomUser(AbstractUser):
    username = None
    email = models.EmailField(_("email address"), unique=True)
    
    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = []
    
    objects = CustomUserManager()
    
class UserProfile(models.Model):
    user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name="userProfile")
    user_guid = models.UUIDField(
        default=uuid.uuid4,
        unique=True,
        editable=False
    )
    user_type = models.IntegerField(choices=UserType.choices(), default=UserType.BUYER)
    wallet_balance = models.FloatField()
    created_at = models.DateTimeField(auto_now=True)
    updated_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        ordering = ['created_at' ]  # Corrected the ordering syntax
#My Serializer
CustomUser = get_user_model()

class UserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = ['user_guid', 'user_type', 'wallet_balance', 'created_at', 'updated_at']
        read_only_fields = ['user_guid', 'created_at', 'updated_at']

class CustomUserCreateSerializer(DjoserUserCreateSerializer):
    userProfile = UserProfileSerializer()

    class Meta:
        model = CustomUser
        fields = ['id', 'email', 'password', 'userProfile']
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        user_profile_data = validated_data.pop('userProfile')
        user = CustomUser.objects.create_user(**validated_data)
        
        UserProfile.objects.create(user=user, **user_profile_data)
        return user
#settings.py
# django auth model
AUTH_USER_MODEL = 'users.CustomUser'

# djoser settings
DJOSER = {
    'SERIALIZERS': {
        'user_create': 'users.v1.serializers.CustomUserCreateSerializer',
        'user': 'users.v1.serializers.CustomUserCreateSerializer',
        'current_user': 'users.v1.serializers.CustomUserCreateSerializer',
    }
}

Error : raise ValueError(
ValueError: Cannot assign “{‘user_type’: 1, ‘wallet_balance’: 0.0}”: “CustomUser.userProfile” must be a “UserProfile” instance.

The code you have in create looks to follow what DRF recommends: Serializers - Django REST framework

With the error you’re getting, you should be able to use the full stacktrace to work out where it’s coming from. Your code is trying to assign the user profile, which your custom code isn’t doing, so I’d expect the error is coming from elsewhere, which the stacktrace should help you narrow down.

1 Like

@theorangeone , thank you for your reply. I’m trying to figure it out.

if somebody faced this same problem, here is solution