1 回答

TA貢獻(xiàn)2019條經(jīng)驗(yàn) 獲得超9個(gè)贊
對(duì)于這個(gè)問(wèn)題我沒(méi)有找到完全令人滿意的答案,但最終默許了這個(gè)解決方案,因?yàn)樗葟?fù)制粘貼更好。
您可能無(wú)法繼承視圖集操作,但您肯定可以繼承各個(gè)方法,然后在子級(jí)中覆蓋它們并在頂部拋出一個(gè)裝飾器。這導(dǎo)致了這個(gè)結(jié)構(gòu):
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 關(guān)注
- 183 瀏覽
添加回答
舉報(bào)