My query is quite simple, I have a model Vendor
in my Django REST app. What I want is to use a get response with a few ID and get back all the respective models with these ID. The GET url pattern could be something like this: 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. 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.
The view is as simple as: And finally the template: The magic happens inside the UserFilter class. We simply have to pass the request.GET data to the UserFilter class, along with the QuerySet we want to filter. It will generate a Django Form with the search fields as well as return the filtered QuerySet.
Here Student Model is having state and city as positiveInteger which provides the ID of state model and city model. In this case, when the student details required for every object we should query again to get state name and city name. By using extra ( {}) in the Django ORM we can filter state and city objects with single query
If you want to filter students using IN, then this would do: Students.objects.filter (id__in=id_tuple) As stepnak stated to do an in query the correct syntax is filter (id__in=id_tuple)
When a value is expected to be retrieved from the database then the filter queryset section of the queryset oriented extraction comes into play. Mentioning a filter of a specific column will help us to filter and pull those corresponding values alone from the queryset retrieved.
(Unfortunately I do not know django REST, so here is a pure django solution)
Using the ListAPIView
you can access the URL (or GET) params and modify the queryset.
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
Overriding get_queryset
will control what results we get from hitting the view
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".
filter(id__in=ids)
lets you say select stuff that has an value in this list of ids
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With