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
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.
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.
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.
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.
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
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With