'Adding the member in django REST framework serializer

I am using serializer of Django REST framework

I have this Serializer and class.

This serializes data and passes as json.

class SpotSerializer(serializers.Serializer):
    spot_id = serializers.IntegerField()
    another_id = serializers.IntegerField()


class Spot: 
    def __init__(self, spot_id,another_id)
        self.spot_id = spot_id
        self.another_id = another_id

Now I want to add the another variable not the class member such as

class SpotSerializer(serializers.Serializer):
    spot_id = serializers.IntegerField()
    another_id = serializers.IntegerField()
    another_name = Another.objects.get(id=another_id).name // adding

This code doesn't show error but no another_name field is appeared in json.

So is it possible?



Solution 1:[1]

Yes, you have two choices here. If its okay for you to only read the field, you can use a SerializerMethodField:

class SpotSerializer(serializers.Serializer):
    spot_id = serializers.IntegerField()
    another_id = serializers.IntegerField()
    another_name = serializers.SerializerMethodField()


    def get_another_name(self, obj):
      return Another.objects.get(id=self.kwargs['another_id']).name

In case you want to also update the value, you could use your own field:


class SpotSerializer(serializers.Serializer):
    spot_id = serializers.IntegerField()
    another_id = serializers.IntegerField()
    another_name = AnotherNameField()

class AnotherNameField(serializers.RelatedField):
    def get_queryset(self):
        return Another.objects.all() # maybe pre-filter

    def to_internal_value(self, data):
        # Update the field value as needed

    def to_representation(self, value):
         # Return the "string" value of the field

I am not sure how exactly the second option would look in your case, but I hope it's a starting point.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1