custom serializer list of objects in django
To create a custom serializer for a list of objects in Django, follow these steps:
- Create a serializer class for the individual object. This is done using Django's built-in serializers module:
from rest_framework import serializers
class MyObjectSerializer(serializers.Serializer):
field1 = serializers.CharField()
field2 = serializers.IntegerField()
...
- Create a serializer class for the list of objects. This serializer should include a list field that uses the serializer for the individual object:
class MyObjectListSerializer(serializers.Serializer):
my_objects = MyObjectSerializer(many=True)
- Use the list serializer in your view or API endpoint:
class MyView(APIView):
def get(self, request):
my_objects = MyObject.objects.all()
serializer = MyObjectListSerializer({'my_objects': my_objects})
return Response(serializer.data)
In this example, MyObject is the model representing the objects you want to serialize. The get method of the MyView class fetches all the objects and passes them to the list serializer. The serializer's data attribute is returned in the response.
原文地址: https://www.cveoy.top/t/topic/1p0 著作权归作者所有。请勿转载和采集!