【发布时间】:2018-08-07 00:41:40
【问题描述】:
我正在使用 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 framework - filtering against query param
显然是 DRF 文档:http://www.django-rest-framework.org/api-guide/filtering/#filtering-against-the-current-user
【问题讨论】:
-
如果我正确理解了您的问题,您需要使用此网址进行过滤:
http://localhost:8000/Api/Identification/search/?NumeroIdentification=NUA_value。使用 requests 库尝试使用 params 参数传递它:response = requests.get(url, params={'NumeroIdentification': NIU}, headers={'Authorization': 'JWT {}'.format(mytoken)}) -
是的,正是我所期望的!请您分享您的消息作为答案以验证它吗?
标签: python django django-rest-framework