我正在使用Django REST Framework设计一个API端点,并希望它在以下端点接受GET、修补程序和PUT方法:
/department/<department_pk>/details/population/部门模型和DepartmentPopulationDetail模型之间存在1:1的关系( DepartmentPopulationDetail模型有一个名为departmnet的FK )。GET方法应该返回DepartmentPopulationDetail模型实例,PUT和修补程序应该允许编辑同一个实例(而不需要提供DepartmentPopulationDetail PK)。
我设法让端点返回所需的GET响应,不允许删除或创建,但无法让它接受PUT或修补程序请求--实际上,从未调用过update方法。如何获得我的视图来接受PUT和修补程序请求并编辑适当的模型?
urls.py
...
url(r'^departments/(?P<department_pk>[0-9]+)/details/population',
include(department_urls.department_study_population_router.urls,
namespace='department_study_population')),
...
serializers.py
class DepartmentStudyPopulationSerializer(serializers.ModelSerializer):
class Meta:
model = DepartmentStudyPopulation
fields = ('pk', 'department', 'age', 'zip_code')
read_only_fields = ('pk', 'department')
views.py
class DepartmentStudyPopulationViewSet(viewsets.ModelViewSet):
queryset = DepartmentStudyPopulation.objects.all()
serializer_class = DepartmentStudyPopulationSerializer
http_method_names = ['get', 'put', 'patch']
def update(self, request, department_pk, **kwargs):
queryset = departmentStudyPopulation.objects.all()
study_population = get_object_or_404(queryset, department_pk=department_pk)
serializer = DepartmentStudyPopulationSerializer(
study_population, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)发布于 2016-06-08 14:53:20
为什么update() 方法从未被称为?
这是因为您错误地定义了urls。
这个url
'departments/(?P<department_pk>[0-9]+)/details/population'使用路由器生成以下urls。
'departments/(?P<department_pk>[0-9]+)/details/population/' # handle list views
'departments/(?P<department_pk>[0-9]+)/details/population/<pk>/' # handle detail views因此,只有在下面的url上有请求时,update()方法才会被调用,pk表示DepartmentStudyPopulation对象的id。
'departments/(?P<department_pk>[0-9]+)/details/population/<pk>/'
那么,如何在所需的url上处理update 和 retrieve 请求?
您需要进行一些更改,以处理下面所需的url端点上的update和retrieve请求。
/department/<department_pk>/details/population/首先,您应该使用RetrieveUpdateAPIView而不是ModelViewSet,因为您只需要处理detail路由。此泛型视图只允许GET、PUT和PATCH方法。
其次,您正在使用department_pk url来获取对象实例,方法是对department_pk字段而不是DepartmentStudyPopulation对象的pk字段进行过滤。您应该在视图中指定值为lookup_field和lookup_url_kwarg的department_pk,DRF将处理实例检索。
最终代码:
views.py
class DepartmentStudyPopulationDetailView(generics.RetrieveUpdateAPIView):
queryset = DepartmentStudyPopulation.objects.all()
serializer_class = DepartmentStudyPopulationSerializer
lookup_field = 'department_pk'
lookup_url_kwarg = 'department_pk'urls.py
url(r'^departments/(?P<department_pk>[0-9]+)/details/population', DepartmentStudyPopulationDetailView.as_view())发布于 2016-06-08 14:48:37
您将需要一个不同的URL来处理这些情况。
Create意味着您的DepartmentStudyPopulation是新的,并且没有主键(它是在createion上生成的)。
update将需要一个包含主键的url,以便Django知道要更新什么对象。
(显示URL的文件将有助于解决这个问题,因为我们不知道它们的路由到哪里)。
https://stackoverflow.com/questions/37705233
复制相似问题