本文介绍了如何只显示Django序列化器中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 rest_serializer模块实现Django REST API框架:

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

当前输出为:

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

如何将其显示为json列表:

How do I display just this as a json list:

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

以下是我的序列化器:

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


推荐答案

您可以覆盖由list 方法http://www.django-rest-framework.org/api-guide/generic-views/#listmodelmixin rel = nofollow noreferrer> listmodelmixin :

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

这篇关于如何只显示Django序列化器中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 21:33