How to display only values in Django Serializers?

☆樱花仙子☆ 提交于 2020-08-04 05:55:47

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/46125398/how-to-display-only-values-in-django-serializers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!