我正在为模型编写自定义创建方法:
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是我正在使用的视图。
答案 0 :(得分:0)
我发现代码有两点错误:
TripReportSerializer(instance).data
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)