Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

django - best practice to add/remove single objects from a many to many field via generic api view

So I have a view like this

class MemberRolePutDeleteView(MultipleFieldMixin, PutDeleteAPIView):
    """
    An API view to create member-roles as well as delete the same.
    Although the role is returned by the get_object method, we only
    remove the same from the referenced member, and don't delete/modify it.
    """

    queryset = api_models.Role.objects.all()
    permission_classes = [IsAuthenticated, ManageRoles]
    lookup_fields = ['cluster_id', 'pk']

    def destroy(self, request, *args, **kwargs):
        role = self.get_object()
        member = api_models.Member.objects.get(user__id=self.kwargs['user_id'], cluster=role.cluster)
        member.roles.remove(role)
        return Response(status=204)

    def update(self, request, *args, **kwargs):
        role = self.get_object()
        member = api_models.Member.objects.get(user__id=self.kwargs['user_id'], cluster=role.cluster)
        member.roles.add(role)
        return Response(status=204)

I get the object I want via the get_object method. Now, in the api view, I want to remove the same from member.roles or add to it, instead of actually deleting the object.

I am doing this right now by overriding the methods. However, I think that there is a better way to achieve this. Can someone please help me to do the same? thanks a lot!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...