Home > OS >  How can i insert a serial number for the following query in Django?
How can i insert a serial number for the following query in Django?

Time:07-31

Info: I want to a serial number to come along with all objects in queryset using Django rest framework instead of object ID. The example image is below. the serial start from first object in queryset list.

This is a Example i want to get!

[
    {
        "id": 3,
        "channel": 25,
        "live_stream_id": "38IEolI8f-w",
        "serial": 1
    },
    {
        "id": 2,
        "channel": 22,
        "live_stream_id": "S2Oh4cqEmOg",
        "serial": 2
    },
    {
        "id": 79,
        "channel": 34,
        "live_stream_id": "4NfbS0YfuFo",
        "serial": 3
    }
]

serializers.py

class LiveStreamSerializer(serializers.ModelSerializer):
    serial = 0

    def get_serial(self):
        return self.serial  = 1

    serial = serializers.SerializerMethodField('get_serial')

    class Meta:
        model = LiveStream
        fields = ['id', 'channel', 'live_stream_id', 'serial']

views.py

class LiveStreamListApi(generics.ListAPIView):

    queryset = LiveStream.objects.all()
    serializer_class = LiveStreamSerializer

CodePudding user response:

I think you can add the additional field by customizing the get function of the ListAPIView class.

class LiveStreamListApi(generics.ListAPIView):
    queryset = LiveStream.objects.all()
    serializer_class = LiveStreamSerializer

    def get(self, request):
        live_streams = LiveStreamSerializer(self.get_queryset(), many=True).data
        for index, _ in enumerate(live_streams)
            live_streams[index]['serial'] = index   1
        return Response(live_streams)

    
    
  • Related