Add: UserProfile & User model serializers
This commit is contained in:
parent
efe6d89caa
commit
fceca8258a
1 changed files with 42 additions and 0 deletions
42
backend/api/user/serializers.py
Normal file
42
backend/api/user/serializers.py
Normal 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
|
||||
|
Loading…
Add table
Reference in a new issue