简体   繁体   English

Django:按多个ID过滤queryset

[英]Django: filter queryset by multiple ID

My query is quite simple, I have a model Vendor in my Django REST app. 我的查询非常简单,我的Django REST应用程序中有一个模型Vendor What I want is to use a get response with a few ID and get back all the respective models with these ID. 我想要的是使用带有几个ID的get响应,并使用这些ID取回所有各个模型。 The GET url pattern could be something like this: r'^api/vendors?id=1,2,3' . GET网址格式可能是这样的: r'^api/vendors?id=1,2,3'

What I'm thinking of right now is to use ListAPIView , and in the list method filter my queryset with all the id in the url. 我现在想到的是使用ListAPIView ,并在list方法中使用URL中的所有ID过滤我的queryset。 But I'm not sure exactly how to achieve this (filtering queryset with a list of id, I'm very new to both Python and Django), so if anyone can provide any advice on this it would be greatly appreciated. 但是我不确定究竟如何实现(用id列表过滤查询集,我对Python和Django都是陌生的),因此,如果有人可以提供任何建议,将不胜感激。

(Unfortunately I do not know django REST, so here is a pure django solution) (不幸的是我不知道Django REST,所以这里是一个纯django解决方案)

Using the ListAPIView you can access the URL (or GET) params and modify the queryset. 使用ListAPIView您可以访问URL(或GET)参数并修改查询集。

class MyVendorView(ListAPIView):
    # attributes

    def get_queryset(self):
        id_string = self.request.GET.get('id')
        if id_string is not None:
            ids = [int(id) for id in id_string.split(',')]
            return Vendor.objects.filter(id__in=ids)

        else:
            return Vendor.objects.all()

    # other methods

please note that I'm ingoring any attributes or other attributes needed 请注意,我正在添加所需的任何属性或其他属性

What's happening here then? 那这是怎么回事?

  • Overriding get_queryset will control what results we get from hitting the view 覆盖get_queryset将控制我们从点击视图中获得的结果

  • self.request.GET.get('id') Will extract the value of the id query parameter from the url like so localhost:8000/api/vendors?id=1,2,3 the result will be a string "1,2,3". self.request.GET.get('id')将从URL中提取id查询参数的值,例如localhost:8000/api/vendors?id=1,2,3 ,结果将为字符串“ 1, 2,3“。

  • filter(id__in=ids) lets you say select stuff that has an value in this list of ids filter(id__in=ids)允许您说选择在此ID 列表中具有值的东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM