dsimond
dsimond

Reputation: 113

How to serialize multiple models in on serializer with Django?

I try to combine multiple serializers into 1 so I don't have to do multiple fetch on the front end for the same page. Seems that I must use SerializerMethodField.

My views is quite simple :

@api_view(['GET'])
def get_user_profile_by_name(request, name):
    try:
        user_profile = UserProfile.objects.get(display_name=name.lower())
        serializer = UserProfileSerializer(user_profile, many=False)
        return Response(serializer.data)
    except ObjectDoesNotExist:
        message = {'detail': 'User does not exist or account has been suspended'}
        return Response(message, status=status.HTTP_400_BAD_REQUEST)

As this can be accessed by Anonymous user, I can't use request.user All models I want to access inside UserProfileSerializer are related to UserProfile. So I dont really know how to setup my serializer. ( I have more serializer to combine but I limited this to one serializer inside the serializer for the example )

class UserProfilePicture(serializers.ModelSerializer):
    class Meta:
        model = UserProfilePicture
        fields = '__all__'


class UserProfileSerializer(serializers.ModelSerializer):
    profile_picture = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = UserProfile
        fields = '__all__'

    def get_profile_picture(self, obj):
        # What to do here ?

I struggle to understand how to acces " user_profile " object from UserProfileSerializer in order to query the right UserProfilePicture object and return the data combined inside UserProfileSerializer.

Upvotes: 0

Views: 1958

Answers (1)

Roman Miroshnychenko
Roman Miroshnychenko

Reputation: 1564

You haven't shown your models nor described the relationship between UserProfile and UserProfilePicture. But if a profile picture is a one-to-one field of UserProfile you can use a child serializer as a field of a parent serializer:

class UserProfileSerializer(serializers.ModelSerializer):
    profile_picture = UserProfilePicture(source='profile_picture', read_only=True)

Upvotes: 1

Related Questions