Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display only values in Django Serializers?

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
like image 285
H C Avatar asked Sep 08 '17 22:09

H C


People also ask

How do serializers work in Django?

The serializers work in a way similar to Django’s Form classes. The ModelSerializer class provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields and it will automatically generate validators for the serializer.

What should be the name of the serializer field?

But the name of the serializer field should be the same as the foreign key field name class ItemSerializer (serializers.ModelSerializer): category = serializers.SlugRelatedField (read_only=True, slug_field='title') class Meta: model = Item fields = ('id', 'name', 'category') Highly active question.

What is Django-REST-framework-serializer-extensions?

The django-rest-framework-serializer-extensions package provides a collection of tools to DRY up your serializers, by allowing fields to be defined on a per-view/request basis. Fields can be whitelisted, blacklisted and child serializers can be optionally expanded.

What is a serializer_field_mapping in Salesforce?

Called to generate a serializer field that maps to a standard model field. The default implementation returns a serializer class based on the serializer_field_mapping attribute. Called to generate a serializer field that maps to a relational model field.


2 Answers

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
like image 177
spectras Avatar answered Oct 09 '22 10:10

spectras


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))
like image 44
Brown Bear Avatar answered Oct 09 '22 12:10

Brown Bear