-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?

1
  • 2
    if you are getting JSON format in serializer_data then iterate and add a field in it. Commented Dec 24, 2020 at 9:30

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.