DRF-创建一个Viewset Mixin / Baseclass来继承一个viewset-action

时间:2020-10-14 19:13:59

标签: python django inheritance django-rest-framework

我有一个网站,该网站实质上是我所参与的DnD活动的维基。因此,该网站上有许多有关生物,人物,位置等的文章。我想使用Viewset来轻松访问它们,并想使用Viewset操作(与自定义路由器一起)来查找不是通过pk而是通过各种查询参数的单个记录。

我已经有一些适合的方法,现在我想对其应用一些继承,以免重复我自己。我想做的是这样的:

class WikiBaseViewset (viewsets.ModelViewSet):
    detail_with_params_url_pattern_suffix: str

    @action(detail=True, url_name="detail-params", url_path=detail_with_params_url_pattern_suffix)
    def detail_through_params(self, request, **kwargs):
        if self.detail_with_params_url_pattern_suffix == "":
            raise InvalidViewsetURLException("URL of view 'detail_through_params' of WikiBaseViewset is not defined!")

        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()
    detail_with_params_url_pattern_suffix = "(?P<name__iexact>.+)"

但是,我为装饰器绝对需要基类中的URL参数而苦苦挣扎。否则,由于NameError抱怨未定义detail_with_params_url_pattern_suffix,导致代码无法编译。如果您要在基类中设置detail_with_params_url_pattern_suffix=""以便在编译代码时不会出现错误,那就没关系了,因为到目前为止,我实验中的装饰器仍会获取该变量的值来自WikiBaseViewset而非CharacterViewSet

如何重写我的BaseClass使其起作用?甚至有办法吗?

0 个答案:

没有答案