我使用Django并有一个视图来获取/插入数据库中的一些记录。这是我的代码:
class JSONResponse(HttpResponse):
"""
An HttpResponse that renders its content into JSON.
"""
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
@api_view(('GET','POST'))
@renderer_classes((TemplateHTMLRenderer,))
@csrf_exempt
def cours_list(request):
if request.method == 'GET':
data = JSONParser().parse(request)
results = Lesson.objects.get(discipline=data.discipline)
return Response({'cours': results}, template_name='search_results.html')
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = LessonSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JSONResponse(serializer.data, status=201)
return JSONResponse(serializer.errors, status=400)
因此,为了获取数据,我使用GET并插入新记录,我使用POST。首先,这是正确的方法吗?我曾经读过,无论情况如何,使用GET都是一个坏主意。 此外,GET代码实际上并没有工作(我收到了错误的请求错误),而且似乎是来自JSONParser,无法解析请求。
EDIT1
以下是发送的请求:
GET http://127.0.0.1:8000/cours/?{%22discipline%22:%22Mathematiques%22,%22localisation%22:%22%22}
EDIT2
我尝试打印requet.GET
,这就是它给出的内容:
<QueryDict: {'{"discipline":"Mathematiques","localisation":""}': ['']}>
尝试访问request.data['discipline']
时,会说:
django.utils.datastructures.MultiValueDictKeyError: "'discipline'"
答案 0 :(得分:1)
我应该使用GET或POST来检索结果Django
要检索使用GET
我曾经读过,无论情况如何,使用GET都是一个坏主意
完全没有,只要您的GET操作不包含任何副作用(例如,在您的GET方法中,您只是从数据库中读取。
GET代码实际上没有工作(我收到了错误的请求错误)
data2 = JSONParser().parse(request) # you used data2
results = Lesson.objects.get(discipline=data.discipline) # and you used data
^
|____ data? data2?
你需要像这样传递GET参数url/?param1=value1
要读取该值,请使用param1 = request.GET['param1']
,param1将为字符串value1
你正在做的事情是没有传递一个值:
GET http://127.0.0.1:8000/cours/?{%22discipline%22:%22Mathematiques%22,%22localisation%22:%22%22}
这就是为什么你得到一个空值['']
<QueryDict: {'{"discipline":"Mathematiques","localisation":""}': ['']}>
如果需要,您可以将整个数据作为JSON字符串传递,但我更喜欢将其分解为:
url/?discipline=Mathematiques&localisation=Quelquechose
与
discipline = request.GET['discipline']
localisation = request.GET['localisation']
答案 1 :(得分:1)
通常使用GET方法进行信息检索,请参阅HTTP/1.1: Method Dediniton, 9.3:
GET方法意味着检索任何信息(以。的形式) entity)由Request-URI标识。如果Request-URI引用 数据生成过程,它是生成的数据 作为响应中的实体而不是源文本返回 过程,除非该文本恰好是过程的输出。
对于POST方法,最好使用POST请求提交新数据,请参阅HTTP/1.1: Method Dediniton, 9.5:
POST方法用于请求源服务器接受 请求中包含的实体作为资源的新下属 由请求行中的Request-URI标识。 POST旨在 允许统一的方法来涵盖以下功能:
................................................................ - Providing a block of data, such as the result of submitting a form, to a data-handling process; - Extending a database through an append operation.
另请查看Which HTTP methods match up to which CRUD methods?,它会让您更清楚地了解如何以及何时使用特定的HTTP方法,可帮助您进行下一步的开发。
祝你好运!