Django Rest框架:从没有request.getlist的query_params中获取列表 [英] Django Rest Framework: getting lists from query_params without request.getlist

查看:2039
本文介绍了Django Rest框架:从没有request.getlist的query_params中获取列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用序列化器来验证我们基于非模型的服务方法中的数据。这对于POST当然是非常适用的,但是对于GET来说,一般来说,如果query_params中的内容不复杂(不是列表或嵌套)。但是如果我有这样的东西:

We use serializers to to validate the data coming into our non-model based service methods. This works great for POSTs as JSON of course but also for GETs generally if the content in the query_params is not complex (not lists or nested). However if I have something like this:

class RequestSerializer(Serializer):
   objects = ListField(child=PrimaryKeyRelatedField(queryset=Foo.objects.all()), allow_empty=False)
   choice = ChoiceField(choices=my_choices)

,而在客户端上,我只是使用这样的GET:

and on the client I just use a GET like so:

$.ajax({
   type: "GET",
   url: '...',
   data={
      "objects":[1,2,3],
      "choice":"mychoice"
      ...

如果我使用POST而不是GET并设置contentType为application / json,但这并不被 HTTP规范。如果能够处理简单的列表使用情况,则不需要执行以下操作:

this works if I use POST instead of GET and set the contentType to "application/json" but this is not condoned by the HTTP spec. It would be nice to be able to handle the simple list use case without doing something like:

request_serializer = RequestSerializer(data={"objects" :request.query_params.getlist("objects[]")})

有没有一些明显的串行化技巧,我错过了告诉串行器如何获取一个列表(objects = x& objects = y& objects = z)而不用手动调用 request.getlist ?其他人为此做了什么,这似乎是一个常见的用例?

Is there some obvious serializer trick I am missing that tells the serializer how to fetch a list(objects=x&objects=y&objects=z) without manually calling request.getlist? What is everyone else doing for this, it seems like a common use case?

编辑:
我找到了这篇文章,但接受的答案是使用 request.getlist 这不是我想要的。

I did find this post earlier but the accepted answer is using request.getlist which is not what I want.

推荐答案

答案是使用jQuery ajaxSettings

The answer is to use the jQuery ajaxSettings

$.ajaxSettings.traditional = true;

如果您在模板中使用jQuery,从我正在阅读的文本中可能会使用整个项目使用Django,因为它似乎没有受到与其他语言相同的限制。

if you are using jQuery in your templates and from what I am reading it should be probably used for the entire project using Django because it does not seem to suffer from the same limitations as other languages.


从jQuery 1.4开始,$ .param()方法递归地深入深度对象
以适应现代脚本语言和框架
,如PHP和Ruby on Rails。

As of jQuery 1.4, the $.param() method serializes deep objects recursively to accommodate modern scripting languages and frameworks such as PHP and Ruby on Rails.

使这个错误导致变量作为objects []和在 ListField 中处理HTML列表的代码因为param已被替换,所以永远不会被调用。

Leaving this false causes the variable to come through as "objects[]" and the code that would handle HTML lists in ListField never gets invoked because the param has been replaced.

这篇关于Django Rest框架:从没有request.getlist的query_params中获取列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆