1 回答
TA贡献2019条经验 获得超9个赞
对于这个问题我没有找到完全令人满意的答案,但最终默许了这个解决方案,因为它比复制粘贴更好。
您可能无法继承视图集操作,但您肯定可以继承各个方法,然后在子级中覆盖它们并在顶部抛出一个装饰器。这导致了这个结构:
class WikiBaseViewset (viewsets.ModelViewSet):
detail_with_params_url_pattern_suffix: str
def detail_through_params(self, request, **kwargs):
model = self.serializer_class.Meta.model
instance = get_object_or_404(model, **kwargs)
serializer = self.get_serializer(instance)
return Response(serializer.data)
class CharacterSerializer (serializers.HyperlinkedModelSerializer):
class Meta:
model = wiki_models.Character
fields = '__all__'
class CharacterViewSet(WikiBaseViewset):
"""Called with URLs: character, character/<str: name>"""
serializer_class = CharacterSerializer
queryset = wiki_models.Character.objects.all()
@action(detail=True, url_name="detail-params", url_path="(?P<name__iexact>.+)")
def detail_through_params(self, request, **kwargs):
return super().detail_through_params(request, **kwargs)
- 1 回答
- 0 关注
- 110 浏览
添加回答
举报