Jack022
Jack022

Reputation: 1287

Filter json records in Django Rest Framework

I created a DRF API endpoint in order to be able to grab some data to my database and show it on my Django page using Jquery.

My sample data looks like this:

{
    "item": "Someitem",
    "Price": 120,
    "Status": "Free"
},
{
    "item": "SecondItem",
    "Price": 90,
    "Status": "Taken"
},

So if I retrieve the endpoint from JQuery to this link: http://127.0.0.1:8000/tst/, I'll get all the records and have all of them shown in my web page. But what if, for example, I only want to retrieve only the records whose Status field is set to Taken? Is there any way to edit the DRF request so that it points to http://127.0.0.1:8000/tst/Taken? Or instead, if the user wants to retrieve all the others with the status set to Free, it will point to http://127.0.0.1:8000/tst/Free? I know I could do it with jquery, but I would actually like to do it server-side.

I tried with this:

queryset = tst.objects.filter(Status="Taken")

But the problem here, is that it will always take only the Taken records from my DB. In my case, I want to find a way to retrieve Taken sometimes, and Free some other times from the template.

I'm fairly new to DRF, so my setup is pretty basic:

views.py

class tstList(generics.ListCreateAPIView):
    queryset = tst.objects.all()
    serializer_class = tstSerializer


class tstDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = tst.objects.all()
    serializer_class = tstSerializer

url.py

path('tst/', views.tstList.as_view()),
path('tst/<int:pk>/', views.tstDetail.as_view()),

models.py

class tst(models.Model):
    item = models.CharField()
    Price = models.FloatField()
    Status = models.CharField()
   

    def save(self, *args, using=None, **kwargs):
        super(tst, self).save(*args, **kwargs)

Upvotes: 1

Views: 1915

Answers (3)

w411 3
w411 3

Reputation: 3039

You can set the queryset by django filter

queryset = tst.objects.filter(Status="Taken") # make sure the "Taken" is always Capitalized.

Upvotes: 1

Julien Kieffer
Julien Kieffer

Reputation: 1145

Have a look on DRF doc. In your case, I'd suggest you install django_filters, then in your view:

from django_filters.rest_framework import DjangoFilterBackend

class tstList(generics.ListCreateAPIView):
    queryset = tst.objects.all()
    serializer_class = tstSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ('Status',)

Upvotes: 2

lanartri
lanartri

Reputation: 41

a few days ago i found and watched this video and i think it's useful for your question, (about model managers and querysets):

https://www.youtube.com/watch?v=rjUmA_pkGtw

Upvotes: 1

Related Questions