我正在使用 Django Rest API 部分改进我的 Django Web 应用程序,根据针对表字段值的过滤,我有一个问题。
我有这样的序列化器类:
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值,以便根据这个NIU过滤我的表并返回对象。
例如,在我的数据库中我有这个对象:
我想通过我的 API 返回这个对象,但我不知道我的函数 get_queryset 是否写得很好以及我如何编写我的 API 请求。
进入我的 urls.py 文件,我有:
url(r'^search/$', IndividuResearchAPIView.as_view() , name="Research"),
所以我没有按 URL 进行过滤。
我阅读这些帖子是为了获得更多元素:
Django REST framework - filtering against query param
显然是 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。使用请求库尝试使用参数参数传递它:response = requests.get(url, params={'NumeroIdentification': NIU}, headers={'Authorization': 'JWT {}'.format(mytoken)} )。
