Home > Enterprise >  Getting field from another model into my custom serializer
Getting field from another model into my custom serializer

Time:12-05

I am trying to get 'first_name' and 'last_name' field into my serializer that uses a model which has no user information:

This is the serializers.py file:

enter image description here

This is the models.py file (from django-friendship model):

enter image description here

I am also attaching views.py:

enter image description here

CodePudding user response:

In this case I would make a serializer for the user and then use that in the FriendshipRequestSerializer.

class UserSerializer(serializers.ModelSerializer):
    
    class Meta:
        model = User
        fields = ('id', 'first_name', 'last_name',)


class FriendshipRequestSerialiser(serializers.ModelSerializer):
    to_user = UserSerializer(many=False)
    from_user = UserSerializer(many=False)

    class Meta:
        model = FriendshipRequest
        fields = ('id', 'to_user', 'from_user', 'message', ...
        extra_kwargs = ...
  • Related