使用 Django Rest Framework,我正在使用 app_api
在我的应用程序
ModelViewSet
中为 doctor模型创建端点。我在添加额外操作以使用具有
is_verified
装饰器的 verify
方法更新 @action
字段时遇到以下错误。
error at /app_api/viewset/doctor/6/ redefinition of group name 'pk' as group 2; was group 1 at position 38
请找到下面的代码。
urls.py
router = DefaultRouter()
router.register('doctor', views.DoctorViewSet, basename='doctor')
urlpatterns = [
path('viewset/', include(router.urls)),
path('viewset/<int:pk>', include(router.urls)),
]
模型.py
# Doctor Model
class Doctor(models.Model):
name = models.CharField(max_length=100)
designation = models.CharField(max_length=100)
description = models.TextField(blank=True, default='')
is_verified = models.BooleanField(default=False, blank=True)
序列化器.py
# Doctor Model Serializer
class DoctorModelSerializer(serializers.ModelSerializer):
class Meta:
model = Doctor
fields = '__all__'
read_only_fields = ('is_verified',)
# Doctor Partial Update Model Serializer
class DoctorUpdateVerifyModelSerializer(serializers.ModelSerializer):
class Meta:
model = Doctor
fields = ('id', 'name', 'is_verified')
read_only_fields = ('name',)
views.py
class DoctorViewSet(viewsets.ModelViewSet):
serializer_class = DoctorModelSerializer
queryset = Doctor.objects.all()
def get_serializer_class(self):
serializer_class = self.serializer_class
if self.request.method == 'PATCH' and self.action == 'verify':
serializer_class = DoctorUpdateVerifyModelSerializer
return serializer_class
@action(methods=['patch'], detail=True)
def verify(self, request, pk=None):
serializer = self.get_serializer(self.get_object(), data=request.data, partial=True)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
return Response(serializer.data)
现在,当我使用
verify
装饰器添加额外操作来路由方法 @action
时,在访问 /app_api/viewset/doctor/6/ 和 / 的 url 时收到以下错误app_api/viewset/doctor/6/verify/ 其中 6
是 doctor
的主键
error at /app_api/viewset/doctor/6/ redefinition of group name 'pk' as group 2; was group 1 at position 38
如果我从用
detail=True
注释的 verify
方法中删除 @action
,它对于 /app_api/viewset/doctor/6/ 效果很好。我的问题是,如果我有 @action
装饰器和 detail=True
,为什么会生成此错误。
我通过从
router.urls
中删除第二个 path('viewset/<int:pk>', include(router.urls))
即 urls.py
解决了这个问题。
urls.py更新后的代码为
router = DefaultRouter()
router.register('doctor', views.DoctorViewSet, basename='doctor')
urlpatterns = [
path('viewset/', include(router.urls)),
]
我也有相同的错误消息和评论format_suffix_patterns方法修复问题
urlpatterns = [
path('companies/', include(router.urls) )]
# urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html'])