custom serializer for list of custom objects in django example
Here is an example of a custom serializer for a list of custom objects in Django using the Django Rest Framework:
from rest_framework import serializers
from .models import CustomObject
class CustomObjectSerializer(serializers.ModelSerializer):
class Meta:
model = CustomObject
fields = '__all__'
class CustomObjectListSerializer(serializers.ListSerializer):
def create(self, validated_data):
custom_objects = [CustomObject(**item) for item in validated_data]
return CustomObject.objects.bulk_create(custom_objects)
def update(self, instance, validated_data):
instance_mapping = {str(obj.id): obj for obj in instance}
data_mapping = {str(item['id']): item for item in validated_data}
ret = []
for obj_id, data in data_mapping.items():
obj = instance_mapping.get(obj_id, None)
if obj is None:
ret.append(self.child.create(data))
else:
ret.append(self.child.update(obj, data))
for obj_id, obj in instance_mapping.items():
if obj_id not in data_mapping:
obj.delete()
return ret
class CustomObjectViewSet(viewsets.ModelViewSet):
queryset = CustomObject.objects.all()
serializer_class = CustomObjectSerializer
list_serializer_class = CustomObjectListSerializer
def get_serializer_class(self):
if self.action == 'list':
return self.list_serializer_class
return self.serializer_class
In this example, we define a custom serializer for the CustomObject model using the ModelSerializer class provided by Django Rest Framework. We then define a custom list serializer CustomObjectListSerializer that overrides the create and update methods to handle creating and updating a list of objects.
Finally, we define a CustomObjectViewSet that uses the custom list serializer for the list action and the standard serializer for all other actions. This allows us to handle creating and updating a list of objects using the custom list serializer and handle all other actions using the standard serializer.
原文地址: https://www.cveoy.top/t/topic/1qk 著作权归作者所有。请勿转载和采集!