-1

i have these code on my Django

    def get(self, request):
        movie = Movie.objects.all().order_by('name').first()
        serializer = MovieSerializer(movie)
        serializer_data = serializer.data
        return Response(serializer_data, status=status.HTTP_200_OK)

and it returns this data

{
    {
      "description": "Haunted House Near You",
      "id": 1,
      "name": "Scary Night",
    },
    {
      "description": "Netflix and Chill",
      "id": 2,
      "name": "Movie Night",
    },
}

i want to add custom field , called 'alias' like this

{
    {
      "description": "Haunted House Near You",
      "id": 1,
      "name": "Scary Night",
      "alias": "SN"
    },
    {
      "description": "Netflix and Chill",
      "id": 2,
      "name": "Movie Night",
      "alias": "MN"
    },
}

My Question is, how do i add the custom field using ORM on Django?

dexdagr8
  • 297
  • 1
  • 3
  • 11

1 Answers1

2

You can easily add a field based on your object with SerializerMethodField. By default, it looks for get_NameOfField method inside your serializer. Note that this is a read only field which i believe is what you're looking for.

Here is an example which gives the first letter of each word of your object's name.

# serializers.py

class YourSerializer(serializers.ModelSerializer):
    alias = serializers.SerializerMethodField()

    class Meta:
        # class meta stuff

    def get_alias(self, obj):
        return "".join([s[0] for s in obj.name.split()])

This is much more efficient than trying to use an additional query in your view.

Hope that helped.

Guillaume
  • 1,956
  • 1
  • 7
  • 9