使用模型ID列表调用django rest API [英] Call django rest API with list of model ids

查看:34
本文介绍了使用模型ID列表调用django rest API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出有关具有特定模型ID列表的特定模型的端点的最佳方法.我知道我可以使用url(/markers/{id})中的ID查询详细信息终结点,但是我希望能够一次发布多个ID,并从具有这些ID的模型实例接收数据.截至目前,我创建了一个自定义的APIView,如下图所示(MarkerDetailsList),在这里我基本上只是发布ID列表,并定义一个自定义的post方法来解析和查找db中的ID,但是我很难相信这一点.是实现此目标的最佳方法.有没有一种方法可以使用视图集实现相同的目的?我检查了文档并四处搜寻,似乎找不到任何东西.有什么建议吗?

I'm trying to figure out the best way to go about querying an endpoint for specific models with a list of those model ids. I know that I can query the detail endpoint using the id in the url (/markers/{id}), but I'd like to be able to post multiple ids at once and receive data from the model instances with those ids. As of right now, I created a custom APIView seen below (MarkerDetailsList) where I essentially just post a list of ids and define a custom post method to parse and lookup the ids in the db, but I'm finding it hard to believe this is the best way to accomplish this. Is there a way to achieve the same thing using the viewset? I've checked the documentation and searched around and cant seem to find anything. Any suggestions?

class MarkerViewSet(viewsets.ModelViewSet):
    permission_classes = [permissions.AllowAny]
    authentication_classes = ()
    queryset = Marker.objects.all()
    serializer_class = MarkerSerializer

class MarkerDetailList(APIView):
    queryset = Marker.objects.all()
    serializer_class = MarkerSerializer
    permission_classes = [permissions.AllowAny]
    authentication_classes = (JSONWebTokenAuthentication, )

    def post(self, request):
        ids = request.data['mapIds']
        markers = Marker.objects.filter(id__in=ids)
        serializer = MarkerSerializer(markers, many=True)
        return Response(serializer.data)

推荐答案

您可以为此使用 Filter FilterSet .(编写了部分代码,然后找到了 https://stackoverflow.com/a/24042182/2354734 )

You could use a Filter and FilterSet for this. (Wrote part of the code, then found https://stackoverflow.com/a/24042182/2354734)

class ListFilter(django_filters.Filter):
    def filter(self, qs, value):
        if value not in (None, ''):
            integers = [int(v) for v in value.split(',')]
            return qs.filter(**{'%s__%s'%(self.name, self.lookup_type):integers})
        return qs  

class MarkerFilter(django_filters.FilterSet):
    ids = django_filters.NumberFilter(name="id", lookup_type='in')

    class Meta:
        model = Marker
        fields = ['ids']

class MarkerViewSet(viewsets.ModelViewSet):
    queryset = Marker.objects.all()
    serializer_class = MarkerSerializer
    filter_backends = (filters.DjangoFilterBackend,)
    filter_class = MarkerFilter

现在在/markers/?ids = 1,2,3,4上检索

When you now retrieven on /markers/?ids=1,2,3,4

这篇关于使用模型ID列表调用django rest API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆