使用序列化器将多个数据添加到模型中

时间:2018-10-11 06:10:41

标签: django django-rest-framework

下面的代码是存储伪数据并将其添加到数据库中的对象。

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
}

1 个答案:

答案 0 :(得分:0)

您的实现几乎没有问题。

  1. obj未定义
  2. 在请求数据中将活动名称替换为“ i.activity_name”
  3. 将活动名称字段手动添加到序列化器中
  4. 多个保存呼叫
  5. 不处理GET请求
  6. 当您尝试进行POST时,它似乎处理的好多(即使没有保存)。
  7. 不清楚您实际发送的数据。

因此,我假设您发送的数据如下所示:

 {
"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。