Essex
Essex

Reputation: 6128

Django Rest Framework : Filtering against Table Field value

I'm improving my Django Web App with Django Rest API part and I have a question according to filtering against table field value.

I have my serializer class like this :

class IndividuResearchSerializer(serializers.ModelSerializer) :
    class Meta :
        model = Individu
        fields = [
            'id',
            'NumeroIdentification',
            'Nom',
            'Prenom',
            'VilleNaissance',
        ]

My views.py file with this class :

class IndividuResearchAPIView(ListAPIView) :
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication,)
    serializer_class = IndividuResearchSerializer

    def get_queryset(self):
        queryset = Individu.objects.all()
        NIU = self.request.query_params.get('NumeroIdentification')
        queryset = queryset.filter(NumeroIdentification=NIU)

        return queryset

And my pythonic file which let to simulate connexion from another software based to API Rest :

import requests

mytoken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6IkFkbWluIiwiZXhwIjoxNTE5NzMxOTAxLCJlbWFpbCI6InZhbGVudGluQGRhdGFzeXN0ZW1zLmZyIiwib3JpZ19pYXQiOjE1MTk3MjgzMDF9.493NzJ4OUEzTKu5bZsZ9UafMwQZHz9pESMsYgfd0RLc"
url = 'http://localhost:8000/Api/Identification/search/'


NIU = "I-19312-00001-305563-2"

response = requests.get(url, NIU = NIU, headers={'Authorization': 'JWT {}'.format(mytoken)})

print(response.text)

I would like to enter a NIU value into my request in order to filter my table and return the object according to this NIU.

For example, in my database I have this object :

enter image description here

I would like to return this object thanks to my API but I don't know if my function get_queryset is well-writen and How I can write my API request.

Into my urls.py file, I have :

url(r'^search/$', IndividuResearchAPIView.as_view() , name="Research"),

So I am not making a filtering by URL.

I read these posts in order to get more element :

Django REST framework - filtering against query param

django rest framework filter

and obviously DRF doc : http://www.django-rest-framework.org/api-guide/filtering/#filtering-against-the-current-user

Upvotes: 2

Views: 544

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47364

You need to use this url to filter: http://localhost:8000/Api/Identification/search/?NumeroIdentification=NUA_value. With requests library try to pass it with params argument: response = requests.get(url, params={'NumeroIdentification': NIU}, headers={'Authorization': 'JWT {}'.format(mytoken)}).

Upvotes: 1

Related Questions