Add: UserProfile & User model serializers

This commit is contained in:
Aroy-Art 2025-01-28 22:09:47 +01:00
parent efe6d89caa
commit fceca8258a
Signed by: Aroy
GPG key ID: 583642324A1D2070

View file

@ -0,0 +1,42 @@
# api/user/serializers.py
from rest_framework import serializers
from .models import UserProfile
from django.contrib.auth.models import User
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ["show_mature"]
def update(self, instance, validated_data):
# Use setattr to assign values to the instance fields
for attr, value in validated_data.items():
setattr(instance, attr, value)
instance.save() # Save the changes to the database
return instance
class UserSerializer(serializers.ModelSerializer):
profile = UserProfileSerializer(source="userprofile", read_only=False)
class Meta:
model = User
fields = ["username", "email", "first_name", "last_name", "profile"]
def update(self, instance, validated_data):
# Extract profile data if it exists
profile_data = validated_data.pop("userprofile", None)
# Update the UserProfile instance
if profile_data:
userprofile_instance = instance.userprofile # The related UserProfile instance
profile_serializer = self.fields["profile"] # Get the nested serializer
profile_serializer.update(userprofile_instance, profile_data) # Update the UserProfile
# Update the User fields
for attr, value in validated_data.items():
setattr(instance, attr, value)
instance.save() # Save the User instance
return instance