如何将模型方法公开给django-rest-framework

时间:2014-09-03 06:52:37

标签: python django rest django-rest-framework

我有一个模型WeddingInvite,它有一个拒绝和接受邀请的方法,如下所示:

class WeddingInvite(models.Model):
     from_user=models.ForeignKey(User,related_name="person_inviting")
     to_user=models.ForeignKey(User,related_name="person_invited")
     wedding=models.ForeignKey(Wedding,related_name="wedding_invite")
     status=models.IntegerField(choices=CHOICES)

     def accept(self):

         attending=Attending(attendant=to_user,wedding=Wedding)
         attendant.save()

         self.status=1
         self.save()

         notification.send([self.to_user],"invite_accepted",{"invitation":self})


     def decline(self):
         self.status=2
         self.save()

如何将方法公开给视图或序列化程序,以便人们可以接受或拒绝 通过django-rest-framework使它可以作为json传递? 以下是序列化程序和视图:

class WeddingInviteList(generics.ListCreateAPIView):
     serializer_class=WeddingInviteSerializer


     def list(self,request,*args,**kwargs):
         wedding_invites=[]

         invited=request.user


         qs=WeddingInvite.objects.filter(Q(to_user=invited))
         for invite in qs:
             wedding_invites.append({invite.from_user,"invited you to a wedding ",invite.wedding})

         return Response(wedding_invites)    

class WeddingInviteSerializer(serializers.ModelSerializer):
      class Meta:
           model=WeddingInvite

如何在视图或序列化程序中启用接受和拒绝方法?

编辑:我意识到有一个序列化方法字段,但它返回一个值。我不知道这是否可以使用,因为我的方法与此示例不同serializer method field

关于这个或任何其他方式的正确方向的一点非常有帮助。

1 个答案:

答案 0 :(得分:6)

下面未经测试的代码,这是我可以采取的方法。

对于序列化程序:

class WeddingInviteResponseSerializer(serializers.Serializer):
    response = serializers.BooleanField(required=True)

对于您的视图,请随意添加更多验证方法和用户检查。

from django.http import Http404
from rest_framework.views import APIView
from .models import WeddingInvite
from .serializers import WeddingInviteResponseSerializer


class WeddingInviteResponseView(APIView):
    serializer_class = WeddingInviteResponseSerializer

    def get_object(self, pk):
        try:
            return WeddingInvite.objects.get(pk=pk)
        except WeddingInvite.DoesNotExist():
            raise Http404

    def post(self, request, pk):
        serializer = self.serializer_class(data=request.DATA)

        if serializer.is_valid():
            response = serializer.data['response']
            invite = self.get_object(pk)

            if response.accept:
                invite.accept()
                return Response({'success': "Wedding Invited accepted"}) status=status.HTTP_200_OK)
            else:
                invite.decline()
                return Response({'success': "Wedding Invited declined"}) status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

最后,只需在您的网址中公开以下结束点:

url(r'^invite/(?P<pk>\d+)/response$', WeddingInviteResponseView.as_view(), name='wedding-invite-response')

希望这有助于指出正确的方向。