简体   繁体   中英

How to pass parameter to get_queryset in Django

I have Django API built in and I have endpoint the return all object. I want the user to provide me with keyword to filter this queryset. What is the best way to do it. and how to do it plz ?

is it in get_queryset? if yes can you help me !?

You have access to the GET parameters (in the querystring ) with self.request.GET [Django-doc] .

So for example if there is a parameter ?category=foo , you can access foo with self.request.GET['category'] , or self.request.GET.get('category') if you want it to return None in case it is missing.

You thus can filter for example with:

from rest_framework import generics
from app.models import SomeModel
from app.serializers import SomeSerializer

class UserList(generics.ListAPIView):
    model = SomeModel

    def get_queryset(self):
        qs = super().get_queryset()
        category = .get('category')
        if category is None:
            return qs
        return qs.filter(category=categry)

just give pass the parameter with some default value:

def get_queryset(self, some_thing=default):
        .
        .
        .

It will work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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