API 端点将列表作为 DRF 中的数据

问题描述 投票:0回答:1

我的 models.py 中有一个名为 Component 的类,并且在 React 中有一个组件 id 数组,我想将它们发布到我的 DRF API,以便我可以获取它们的数据作为我的响应。我想要这样的东西:

请求正文:

{
compIds:[77,54,125],
}

回应:

[
{id:77,name:"SMTH 77", price:120},
{id:54,name:"SMTH 54", price:140},
{id:125,name:"SMTH 77", price:61},
]

这是我的组件模型:

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 = 'قطعات'

我不知道应该如何编写我的序列化器和视图集。

django django-rest-framework
1个回答
0
投票
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)

© www.soinside.com 2019 - 2024. All rights reserved.