下面的代码是存储伪数据并将其添加到数据库中的对象。
obj = [
{
"activity_name": 'test-for-33',
"created_by": 1142,
"activity_start": "2018-10-10 07:56:11+00 ",
"activity_end": "2018-10-10 07:56:11+00 "
},
{
"activity_name": "test-for-55",
"created_by": "1142",
"activity_start": "2018-10-10 07:56:11+00 ",
"activity_end": "2018-10-10 07:56:11+00 "
}
]
views.py
@api_view(['POST', 'GET'])
@parser_classes((JSONParser,))
def insert_data_activity(request):
# Check if seats is a list
# if isinstance(request.data['seat'], list):
# seats = request.data.pop('seat')
if obj is not None:
models = []
for i in obj:
# validate each model with one seat at a time
print(i['activity_name'])
request.data['i.activity_name'] = i['activity_name']
serializer = ActivitySerializer(data=request.data)
serializer.activity_name = i['activity_name']
print("msmssmmmmmmmmmmmmmmm", serializer.activity_name)
serializer.is_valid(raise_exception=True)
serializer.save()
print("saved")
models.append(serializer)
# Save it only after all seats are valid.
# To avoid situations when one seat has wrong id
# And you already save previous
saved_models = [model.save() for model in models]
result_serializer = ActivitySerializer(saved_models, many=True)
# Return list of tickets
return Response(result_serializer.data)
# Save ticket as usual
serializer = ActivitySerializer(data=request.data)
serializer.is_valid(raise_exception=True)
return Response(serializer.data)
在这里,该模型将使用对象进行更新,但是它将空值作为输入并将其存储到数据库中,如下所示。
{
"id": 39,
"activity_name": null,
"acttivity_start": null,
"activity_end": null,
"created": "2018-10-11T05:39:17.329655Z",
"modified": "2018-10-11T05:39:17.329671Z",
"created_by": null
}
答案 0 :(得分:0)
您的实现几乎没有问题。
obj
未定义因此,我假设您发送的数据如下所示:
{
"obj": [{
"activity_name": "st-for-33",
"created_by": 1142,
"activity_start": "2018-10-10 07:56:11+00 ",
"activity_end": "2018-10-10 07:56:11+00 "
},
{
"activity_name": "st-for-33",
"created_by": 1142,
"activity_start": "2018-10-10 07:56:11+00 ",
"activity_end": "2018-10-10 07:56:11+00 "
}
]
}
实现可能如下所示:
@api_view(['POST', 'GET'])
@parser_classes((JSONParser,))
def insert_data_activity(request):
if request.method == 'GET':
# decide what to do in case of GET
return Response({"data" : "something"})
obj = request.data.pop('obj', None)
if obj is not None:
ser = ActivitySerializer(data=obj, many=True)
ser.is_valid()
ser.save()
return Response(ser.data)
# Save ticket as usual
serializer = ActivitySerializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data)
此实现支持一个或多个。同样,这取决于实现序列化器的方式,但是我假设带有__all__
字段的标准ModelSerializer。