![](/img/trans.png)
[英]How to get username of request from ModelViewSet class in Django rest API?
[英]How to send data in GET request in django rest api test
DB中有“顾问”和“价格”表,“价格”有一个“顾问”的外键。 我想获取与特定顾问相关的所有价格记录。 但是当我使用APITestCase
发送 GET 请求时出现错误。
视图.py:
class PriceAPI(APIView):
serializer_class = PriceSerializer
def get(self, request):
consultant_type = request.data.get('type', None)
try:
consultant = Consultant.objects.get(user=request.user, type=consultant_type)
except Consultant.DoesNotExist:
return Response(status=status.HTTP_406_NOT_ACCEPTABLE)
try:
serializer = self.serializer_class(consultant.prices, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
except:
return Response(status=status.HTTP_400_BAD_REQUEST)
测试.py:
class PriceTest(APITestCase):
def setUp(self):
###
def test_get_delete_price(self):
response = self.client.get(
reverse('price'),
data=json.dumps(
{'type': 'sports'}),
content_type='application/json'
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
我收到此错误:
Error
Traceback (most recent call last):
File "D:\programming\Pycharm\Projects\Django Projects\CAPP\capp_api\tests.py", line 394, in test_get_delete_price
content_type='application/json'
File "D:\programming\Pycharm\Projects\Django Projects\CAPP\venv\lib\site-packages\rest_framework\test.py", line 286, in get
response = super().get(path, data=data, **extra)
File "D:\programming\Pycharm\Projects\Django Projects\CAPP\venv\lib\site-packages\rest_framework\test.py", line 194, in get
'QUERY_STRING': urlencode(data or {}, doseq=True),
File "D:\programming\Pycharm\Projects\Django Projects\CAPP\venv\lib\site-packages\django\utils\http.py", line 113, in urlencode
for key, value in query:
ValueError: not enough values to unpack (expected 2, got 1)
此错误与请求中发送的数据有关。 我怎样才能在 GET 请求中做到这一点?
GET 请求无法通过 JSON 主体。 参数可以通过查询字符串传递。 因此,在 test.py 中的数据必须更改,并且在 views.py 中通过request.GET.get('field')
“获取” function 我们可以访问该参数。
测试.py:
response = self.client.get(
reverse('price'),
data={'type': 'sports'}, # This line is changed
content_type='application/json'
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
视图.py:
consultant_type = request.GET.get('type', None)
这个:
'QUERY_STRING': urlencode(data or {}, doseq=True),
让我认为data
应该是一个字典,但是您正在使用json.dumps()
将其转换为字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.