<p>您需要做的是,<a href="https://www.django-rest-framework.org/api-guide/serializers/" rel="nofollow noreferrer">serialize the newly created <strong>^{<cd1>}</strong> instance</a>并使用DRF的<a href="https://www.django-rest-framework.org/api-guide/responses/#creating-responses" rel="nofollow noreferrer"><strong>^{<cd2>}</strong></a>类返回</p>
<pre><code><b>from rest_framework.response import Response</b>
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()
<b># changes
serializer = TripReportSerializer(instance)
return Response(serializer.data)</b></code></pre>