Home > Software design >  Adding a transient ranking field to djangorest class and serializer
Adding a transient ranking field to djangorest class and serializer

Time:06-30

I am new to djangorest and am not sure how to even go about this.

I have a Rest API that takes a post-request (with a list of parameters) and returns a list of items from a model via a serializer. It all works great.

I need to add a "rank" or rather a "relevancy score" to the items in my returned list. I can calculate the rank fine - I am doing it in the REST view - what I don't understand is how to pass the rank back with the serialized model class in the response.

I could create an entirely new object and pass it with the item ids.... but what I would rather do is attach a transient field: {"rank": value } to each item in my list.

Can I do this?

Edit: Was asked for code. Here is what I am trying to do. The serializer class is just a basic all fields serializer.

@api_view(['GET', 'POST'])
def getServices(request):
    ...
    items = getItems(request.data) #returns relevent items
    for item in items:
        rank = calculateRank(item,request.data) #caculates rank based on a ranking model
    ###  
    # I would like add the rank to the item here... unless there is another way?
    ###
    ...
    serializer = ItemSerializer(items, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)

Edit: Additional requirement. I dont always want the rank. The serializer should be able to handle the item with or without a rank field. Or would that require two serializers?

CodePudding user response:

First you can add the rank field into the item.

@api_view(['GET', 'POST'])
def getServices(request):
    ...
    items = getItems(request.data) #returns relevent items
    for item in items:            
        item["rank"] = calculateRank(item, request.data)
    ...
    serializer = ItemSerializer(items, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)

And you can add the rank field in the serializer too.

class ItemSerializer(serializers.ModelSerializer):
    ...
    rank = serializers.IntegerField(read_only = True, required = False)
    
    ...
  • Related