from django.contrib.auth import get_user_model from django.db.models import Q from rest_framework.viewsets import ModelViewSet from api.event.serializers import EventSerializer, PlaceSerializer,\ ActivityTagSerializer, ActivityTemplateSerializer from event.models import Event, Place, ActivityTag, ActivityTemplate User = get_user_model() # classes utilitaires class EventSpecificViewSet(ModelViewSet): """ ViewSet that returns : * rootlevel objects if no Event is specified * OR objects related to the specidied event AND root level objects if an event is specified it passes the event_pk to the save method. Works fine with serializers.EventSpecificSerializer Useful for models that exetends EventSpecificMixin """ def get_queryset(self): """ Warning : You may want to override this method and not call with super """ event_pk = self.kwargs.get('event_pk') queryset = super().get_queryset() if event_pk: return queryset.filter(Q(event=event_pk) | Q(event=None)) return queryset.filter(event=None) def perform_create(self, serializer): event_pk = self.kwargs.get('event_pk') serializer.save(event_pk=event_pk) # ViewSets class EventViewSet(ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. """ queryset = Event.objects.all() serializer_class = EventSerializer def perform_create(self, serializer): serializer.save(created_by=self.request.user) class PlaceViewSet(EventSpecificViewSet): queryset = Place.objects.all() serializer_class = PlaceSerializer class ActivityTagViewSet(ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. """ queryset = ActivityTag.objects.all() serializer_class = ActivityTagSerializer class ActivityTemplateViewSet(ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. """ queryset = ActivityTemplate.objects.all() serializer_class = ActivityTemplateSerializer