API endpoing taking list as data in DRF
I have a class called Component in my models.py and I have an array of Component ids in React and I want to post them to my DRF API so I could get their data as my response. I want something like this:
Request body:
{
compIds:[77,54,125],
}
Response:
[
{id:77,name:"SMTH 77", price:120},
{id:54,name:"SMTH 54", price:140},
{id:125,name:"SMTH 77", price:61},
]
This is my Component model:
class Component(models.Model):
name = models.CharField(max_length=100)
price = models.PositiveIntegerField()
def __str__(self):
return self.name
class Meta:
verbose_name = 'قطعه'
verbose_name_plural = 'قطعات'
I don't know how I should write my Serializer and my viewset.
from rest_framework.views import APIView
from rest_framework import serializers
class ComponentRequestSerializer(serializers.Serializer):
componentIds = serializers.ListField(
child=serializers.IntegerField()
)
class ComponentResponseSerializer(serializers.ModelSerializer):
class Meta:
fields = ["id", "name", "price"]
model = Component
class ComponentAPIView(APIView):
def post(request):
request_data = ComponentRequestSerializer(data=request.data)
request_data.is_valid()
compIds = request_data.validated_data["compIds"]
queryset = Component.objects.filter(id__in=compIds)
response_data = ComponentResponseSerializer(instance=queryset, many=True)
return Response(response_data)