DRF自定义CommonViewSet继承出现MRO方法解析顺序错误如何解决?
报错原因
这个错误是Python的方法解析顺序(MRO)冲突导致的,核心原因是你重复继承了相同的DRF Mixin类:
- DRF自带的
viewsets.ModelViewSet本身已经完整继承了ListModelMixin、CreateModelMixin、RetrieveModelMixin、UpdateModelMixin、DestroyModelMixin这五个功能Mixin - 你自定义的
CommonViewSet已经继承了ModelViewSet,等于已经携带了上述所有Mixin的功能 - 你定义
TagViewSet时又额外继承了ListModelMixin和CreateModelMixin,导致同一个类继承链上出现了重复的父类,Python无法确定方法调用的优先级,因此抛出MRO错误。
修复方案
可根据业务场景二选一:
方案1:保留全量CRUD接口能力
直接删除TagViewSet继承列表里的两个Mixin即可,代码修改为:
class TagViewSet(CommonViewSet): """Manage tags in the database""" authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) queryset = Tag.objects.all() serializer_class = serializers.TagSerializer
这个方案下TagViewSet会默认支持增删改查全量接口,如果你不需要某些接口,可以通过设置http_method_names属性限制允许的请求方法,比如:
# 仅允许GET(列表、详情)和POST请求 http_method_names = ['get', 'post']
方案2:按需选择接口能力
如果你的业务场景中不同的ViewSet需要的接口能力差异很大,不想默认带全量CRUD能力,可以修改CommonViewSet的父类为GenericViewSet,取消默认的Mixin继承:
# 修改CommonViewSet的父类,只保留通用逻辑,不绑定固定接口能力 class CommonViewSet(viewsets.GenericViewSet): """Ensure the models are updated with the requesting user.""" def perform_create(self, serializer): """Ensure we have the authorized user for ownership.""" serializer.save(created_by=self.request.user, updated_by=self.request.user) def perform_update(self, serializer): """Ensure we have the authorized user for ownership.""" serializer.save(updated_by=self.request.user)
修改后你在定义具体ViewSet时再按需继承需要的Mixin即可,原来的TagViewSet继承逻辑不需要改动,不会再出现MRO冲突。
内容的提问来源于stack exchange,提问作者Empusas
相关产品推荐
相关产品推荐

