本文介绍了Django REST序列化程序:创建对象而不保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经开始玩Django REST框架了。我想要做的是使用一些JSON POST请求,从中创建一个Django Model对象,并使用该对象而不保存该对象。我的Django模型叫做SearchRequest。我有的是: @api_view(['POST'])
def post_calculation(request):
如果request.method =='POST':
#JSON到序列化对象
serializer = SearchRequestSerializer(data = request.data)
if(serializer.is_valid()== False) :
return响应(serializer.errors,status = status.HTTP_400_BAD_REQUEST)
mySearchRequestObject = serializer.save()
这样做会创建一个SearchRequest对象,但是立即将其保存到数据库中。我将需要它而不保存。
解决方案
将此方法添加到您的 SearchRequestSerializer
class
def create(self,validated_data):
return SearchRequest(** validated_data)
并在函数 post_calculation
中调用它,而不是保存
,如下所示:
mySearchRequestObject = serializer.create()
I have started to play with the Django REST framework. What I am trying to do is to POST a request with some JSON, create a Django Model object out of it, and use the object without saving it. My Django model is called SearchRequest. What I have is:
@api_view(['POST'])
def post_calculation(request):
if request.method == 'POST':
#JSON to serializer object
serializer = SearchRequestSerializer(data=request.data)
if (serializer.is_valid() == False):
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
mySearchRequestObject = serializer.save()
This does create a SearchRequest object, however saves it into the database right away. I would need it without saving.
解决方案
Add this method to your SearchRequestSerializer
class
def create(self, validated_data):
return SearchRequest(**validated_data)
And call it in function post_calculation
instead of save
, like so:
mySearchRequestObject = serializer.create()
这篇关于Django REST序列化程序:创建对象而不保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!