我正在使用Django Rest API
部分改进我的Django Web App,并根据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"),
所以我没有按网址进行过滤。
我阅读这些帖子是为了获得更多元素:
Django REST framework - filtering against query param
显然是DRF doc:http://www.django-rest-framework.org/api-guide/filtering/#filtering-against-the-current-user
答案 0 :(得分:1)
您需要使用此网址来过滤:http://localhost:8000/Api/Identification/search/?NumeroIdentification=NUA_value
。使用请求库尝试使用params参数传递它:response = requests.get(url, params={'NumeroIdentification': NIU}, headers={'Authorization': 'JWT {}'.format(mytoken)})
。