How to display only values in Django Serializers?

5.5k Views Asked by At

I am implementing Django REST API framework using the 'rest_serializer' module:

Currently the output is:

{
    "count": 86,
    "next": "http://127.0.0.1:8000/state/?page=2",
    "previous": null,
    "results": [
        {
            "state_name": "Alaska"
        },
        {
            "state_name": "California"
        },
        ...
     ]
}

How do I display just this as a json list:

[
     "Alaska",
     "California",
     ...
]

Below are my serializers:

from .models import States
from rest_framework import serializers


class StateSerializer(serializers.ModelSerializer):
    class Meta:
        model = State
        fields = ('state_name',)

view.py

class StateViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = States.objects.values('state_name').distinct();
    serializer_class = StateSerializer
2

There are 2 best solutions below

1
On BEST ANSWER

you cam override list method, provided by listmodelmixin:

from rest_framework.response import Response

class StateViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = States.objects.values('state_name').distinct();
    serializer_class = StateSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        return Response(queryset.values_list('state_name', flat=True))
0
On

Here is what I would do: as you want a custom serialized form for your states, I would implement a custom serializer:

class RawStateSerializer(serializers.BaseSerializer):
    def to_representation(self, obj):
        return obj.state_name

You can then use it normally for reading:

class StateViewSet(viewsets.ModelViewSet):
    queryset = States.objects.values('state_name').distinct();
    serializer_class = RawStateSerializer

Note it only supports reading (it will return just a single string for single GET and a list of strings for list GET). If you want write support as well, you'll need to override .to_internal_value() method.

Lastly, if you only want the special serializer for listing groups, but the regular serializer for other operations, here is how you would do it (based on this answer of mine):

class StateViewSet(viewsets.ModelViewSet):
    queryset = States.objects.values('state_name').distinct();

    def get_serializer_class(self):
        if self.action == 'list':
            return RawStateSerializer
        return StateSerializer