viewsets.py 1.32 KB
Newer Older
1
from rest_framework import permissions
2
3
from rest_framework.decorators import list_route
from rest_framework.response import Response
4
5
6
from rest_framework.viewsets import ModelViewSet

from pushnotifications.api.permissions import IsOwner
7
8
9
from pushnotifications.api.serializers import DeviceSerializer, \
    CategorySerializer
from pushnotifications.models import Device, Category
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32


class DeviceViewSet(ModelViewSet):
    permission_classes = (permissions.IsAuthenticated, IsOwner)
    queryset = Device.objects.all()
    serializer_class = DeviceSerializer

    def get_queryset(self):
        # filter all devices to only those belonging to the current user
        return self.queryset.filter(user=self.request.user)

    def perform_create(self, serializer):
        try:
            serializer.instance = Device.objects.get(
                user=self.request.user,
                registration_id=serializer.validated_data['registration_id']
            )
        except Device.DoesNotExist:
            pass
        serializer.save(user=self.request.user)

    def perform_update(self, serializer):
        serializer.save(user=self.request.user)
33
34
35
36
37
38

    @list_route()
    def categories(self, request):
        categories = Category.objects.all()
        serializer = CategorySerializer(categories, many=True)
        return Response(serializer.data)