簡體   English   中英

Django Rest Framework:根據表字段值過濾

[英]Django Rest Framework : Filtering against Table Field value

我正在使用Django Rest API部分改進我的 Django Web 應用程序,根據對表字段值的filtering ,我有一個問題。

我有這樣的序列化程序類

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

我的views.py文件與此類:

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

還有我的pythonic 文件,它可以模擬來自另一個基於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)

我想在我的請求中輸入一個NIU value ,以便過濾我的表並根據這個NIU返回對象。

例如,在我的數據庫中,我有這個對象:

在此處輸入圖片說明

感謝我的 API,我想返回這個對象,但我不知道我的函數get_queryset是否寫得很好,以及我如何編寫我的 API 請求。

進入我的urls.py文件,我有:

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

所以我沒有按 URL 進行過濾。

我閱讀了這些帖子以獲得更多元素:

Django REST 框架 - 根據查詢參數過濾

django 休息框架過濾器

顯然是 DRF 文檔: http : //www.django-rest-framework.org/api-guide/filtering/#filtering-against-the-current-user

您需要使用此 url 進行過濾: http://localhost:8000/Api/Identification/search/?NumeroIdentification=NUA_value 使用請求庫嘗試使用 params 參數傳遞它: response = requests.get(url, params={'NumeroIdentification': NIU}, headers={'Authorization': 'JWT {}'.format(mytoken)})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM