poulpe/api/event/views.py
2017-07-26 13:11:58 +02:00

101 lines
3 KiB
Python

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, ActivitySerializer
from event.models import Event, Place, ActivityTag, ActivityTemplate, Activity
User = get_user_model()
# classes utilitaires
class EventSpecificViewSet(ModelViewSet):
"""
ViewSet that returns :
* rootlevel objects if no Event is specified
* OR objects related to the specified 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 extends 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)
def perform_update(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(EventSpecificViewSet):
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
def perform_create(self, serializer):
event_pk = self.kwargs.get('event_pk')
serializer.save(event_pk=event_pk)
def perform_update(self, serializer):
event_pk = self.kwargs.get('event_pk')
serializer.save(event_pk=event_pk)
class ActivityViewSet(ModelViewSet):
"""
This viewset automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
"""
queryset = Activity.objects.all()
serializer_class = ActivitySerializer
def perform_create(self, serializer):
event_pk = self.kwargs.get('event_pk')
serializer.save(event_pk=event_pk)
def perform_update(self, serializer):
event_pk = self.kwargs.get('event_pk')
serializer.save(event_pk=event_pk)