ModelViewSet action with two objects as query parameters

670 views
Skip to first unread message

mar...@raesener.de

unread,
Apr 11, 2019, 4:17:21 AM4/11/19
to Django REST framework
Hey DRF Group,

I have a question I couldn't find the documentation about, so if someone might hint me into the right direction I'd be thankful.

So, I'd like to refactor, if possible, the DocumentTemplateView below into the DocumentTemplateModelViewSet - there are DocumentTemplates related to Projects.

So, as you can see in the corresponding url, there are two object id's in the url - ah ModelViewSet @action would also need to handle those two.

Things in advance,

Marius

class DocumentTemplateModelViewSet(ModelViewSet):
queryset = DocumentTemplate.objects.all()
serializer_class = DocumentTemplateSerializer
permission_classes = (HasStaffAccess,)


class DocumentTemplateView(views.APIView):
permissions = (HasStaffAccess,)

def get(self, request, project_pk=None, template_pk=None, **kwargs):
project = Project.objects.get(id=project_pk)
template = DocumentTemplate.objects.get(id=template_pk)
rendered = template.render(project)
return Response(rendered)


urlpatterns = [
url(
r"^document-template/project-(?P<project_pk>\d+)/template-(?P<template_pk>\d+)?$",
DocumentTemplateView.as_view(),
name="api.document.template",
)
]

mar...@raesener.de

unread,
Apr 11, 2019, 6:56:54 AM4/11/19
to Django REST framework
Ok, I have a working solution.

Any comments appreciated :)

class DocumentTemplateModelViewSet(ModelViewSet):
queryset = DocumentTemplate.objects.all()
serializer_class = DocumentTemplateSerializer
permission_classes = (HasStaffAccess,)

    @action(methods=["get"], detail=True, url_path="project-(?P<project_pk>\d+)")
def for_project(self, request, pk, project_pk):
project = Project.objects.get(id=project_pk)
template = self.get_object()

rendered = template.render(project)
return Response(rendered)

the resulting URL is a little different then before but that's only a small issue in this case.
Reply all
Reply to author
Forward
0 new messages