Django REST框架后置数组对象 [英] Django REST framework post array of objects
问题描述
我正在使用 Django REST框架,将API和Angular SPA与Restangular进行通信API。有时我必须添加多个对象来添加,我认为我可以将它们一起发送到数组中并发出一个请求。
当我尝试从错误的输入错误。如果我尝试从REST框架Web界面添加一个对象,我传递对象或数组的对象:
//这个{text:gdhg,},{text:gdhg,},{text:gdhg,}
//或这个[{text:gdhg ,},{text:gdhg,},{text:gdhg,}]
但是我收到ParseError。我错了什么,我必须改变什么或如何正确执行。
我不知道问题是否仍然存在。但是,fiver提出的解决方案对我来说没有效果。
对我来说有用的是只覆盖 get_serializer
方法。
def get_serializer(self,instance = None,data = None,
files = None,many = True,partial = False):
return super(ViewName,self) .get_serializer(实例,数据,文件,
许多,部分)
如果你会注意到我在 get_serializer
的参数中设置默认的 many = True
。
除此之外,没有必要。另外如果您在视图中定义了pre_save和post_save方法,那么希望将列表(iterable)作为参数(就像你所说的那样),这个方法也是不需要的。
正在发布列表)方法不仅仅是一个对象。
def post_save(self,objects ,* args,** kwargs):
在post_save中,obj列表已创建
对象中的obj:
do_something_with(obj)
I am using Django REST framework for API and Angular SPA with Restangular for comunication with the API. Sometimes I have to add more than one objects for adding and I think that I can send them together in array and make one request.
When I try to do this from the Restangular I recive error for Wrong input. If I try to add more then one object from the REST framework web interface I am passing objects or array of objects:
// this { "text": "gdhg", },{ "text": "gdhg", },{ "text": "gdhg", }
// or this [{ "text": "gdhg", },{ "text": "gdhg", },{ "text": "gdhg", }]
But I receive ParseError. Where I am wrong, what I have to change or how to do it properly.
I am not sure if the problem still exist. But the solution suggested by fiver did not work for me.
What works for me is overriding the get_serializer
method ONLY.
def get_serializer(self, instance=None, data=None, files=None, many=True, partial=False): return super(ViewName, self).get_serializer(instance, data, files, many, partial)
If you will notice I am setting default many=True
in arguments of get_serializer
.
Apart from that nothing is required. Overridng of create method is also not required.
Also if you are defining the pre_save and post_save method in the views, expects the list(iterable) as the argument(as you are posting the list) of method not just a single object.
def post_save(self, objects, *args, **kwargs): """ In the post_save, list of obj has been created """ for obj in objects: do_something_with(obj)
这篇关于Django REST框架后置数组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!