Django DRF使用CreateListModelMixin更改序列化器数据

时间:2019-01-12 23:36:16

标签: python django python-3.x django-rest-framework serializer

我有这个类视图,但是我无法修改序列化器数据以插入更多数据(这是必需的,并且需要自动填充)。 因为我一次创建了许多实例,所以序列化程序基于kwargs ['many'] = True。

关于如何向每个序列化器数据添加另一个字段的想法吗?

谢谢

class ReservedServiceView(CreateListModelMixin, ModelViewSet):
queryset = ReservedService.objects.all()
serializer_class = ReservedServiceSerializer
authentication_classes = (authentication.TokenAuthentication,)

def perform_create(self, serializer):
    # Create an event that is a Reflection of the Reserved Service
    serializer_data = self.request.data

    for reserved_service in serializer_data:
        print("--------",reserved_service, flush=True)

        service_id = reserved_service['original_service']

        original_service = Service.objects.get(pk=service_id)

        calendar_event = CalendarEvent()
        calendar_event.name = original_service.name
        calendar_event.description = original_service.description
        calendar_event.date = reserved_service['date']
        calendar_event.type_id = 1
        calendar_event.start_time = reserved_service['start_time']
        calendar_event.end_time = reserved_service['end_time']
        calendar_event.location_id = original_service.location.id
        calendar_event.save()

        reserved_service['associated_event'] = calendar_event.id

    print("**********1", serializer_data)
    print("**********2", self.request.data)
    serializer.save()

基于:

class CreateListModelMixin(object):
def get_serializer(self, *args, **kwargs):
    """ if an array is passed, set serializer to many """
    if isinstance(kwargs.get('data', {}), list):
        kwargs['many'] = True
    return super(CreateListModelMixin, self).get_serializer(*args, **kwargs)

1 个答案:

答案 0 :(得分:2)

我无法正确回答您的问题,但是如果您的问题是您没有得到视图响应中添加到序列化器中的额外字段,那么这里就是答案。

此视图的响应由CreateModelMixin的create方法返回,该方法将serializer.data传递给data的{​​{1}}参数。您无法更新Response,因为它是不可变的对象。因此,要解决此问题,您将必须重写serializer.data方法,如下所示:

create