DRF在create()方法中返回序列化的对象

时间:2018-12-03 19:44:22

标签: python django-rest-framework django-serializer

我正在为模型编写自定义创建方法:

class TripReportViewSet(viewsets.ModelViewSet):
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    serializer_class = TripReportSerializer
    pagination_class = TripReportSetPagination
    # To order by favorite count or 'top':
    queryset = TripReport.objects.all().annotate(count=Count('favoriters')).order_by('-count')
    #queryset = TripReport.objects.all().order_by('-pk')
    filter_backends = (filters.SearchFilter, filters.OrderingFilter)
    search_fields = ('=author__username', '=slug', 'countries__name', )
    ordering_fields = ('pk', )

    def create(self, request, **kwargs):
        countries = request.POST['countries'].split(',')
        countries = list(map(int, countries))
        countries = Country.objects.filter(pk__in=countries)

        instance = TripReport.objects.create(
            author=User.objects.get(pk=request.POST['author']),
            title=request.POST['title'],
            content=request.POST['content'],
        )
        instance.countries.set(countries)
        instance.save()
        return HttpResponse(TripReportSerializer(instance))

我似乎无法得到正确的答复。我想返回序列化的对象,但是

HttpResponse(instance)

HttpResponse(TripReportSerializer(instance))

给我错误的结果。 TripReportSerializer是我正在使用的视图。

2 个答案:

答案 0 :(得分:0)

我发现代码有两点错误:

  1. 要返回序列化器数据,我认为您应该使用TripReportSerializer(instance).data
  2. 其余框架视图通常返回Response对象,该对象是从rest_framework.response.Response导入的

您应该做的另一种修改是使用views get_serializer()方法,以便在序列化程序中填充上下文(视图,格式和请求),这对您而言意味着在代码末尾使用此代码。您的创建方法。

serializer = self.get_serializer(instance)
return Response(serializer.data)

答案 1 :(得分:0)

您需要做的是serialize the newly created Trip instance,然后使用DRF的Response类返回

from rest_framework.response import Response


class TripReportViewSet(viewsets.ModelViewSet):
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    serializer_class = TripReportSerializer
    pagination_class = TripReportSetPagination
    # To order by favorite count or 'top':
    queryset = TripReport.objects.all().annotate(count=Count('favoriters')).order_by('-count')
    # queryset = TripReport.objects.all().order_by('-pk')
    filter_backends = (filters.SearchFilter, filters.OrderingFilter)
    search_fields = ('=author__username', '=slug', 'countries__name',)
    ordering_fields = ('pk',)

    def create(self, request, **kwargs):
        countries = request.POST['countries'].split(',')
        countries = list(map(int, countries))
        countries = Country.objects.filter(pk__in=countries)

        instance = TripReport.objects.create(
            author=User.objects.get(pk=request.POST['author']),
            title=request.POST['title'],
            content=request.POST['content'],
        )
        instance.countries.set(countries)
        instance.save()
        # changes
        serializer = TripReportSerializer(instance)
        return Response(serializer.data)