w
clone your own copy | download snapshot

Snapshots | iceberg

No images in this repository’s iceberg at this time

Inside this repository

views.py
text/x-python

Download raw (2.4 KB)

from django.views.generic.base import TemplateView
from rest_framework import viewsets
from rest_framework.pagination import PageNumberPagination
from rest_framework.parsers import FormParser, MultiPartParser
from rest_framework.filters import OrderingFilter, SearchFilter
from django_filters import BooleanFilter
from django_filters.rest_framework import DjangoFilterBackend, FilterSet
# from django_filters.rest_framework import DjangoFilterBackend
from .models import Attachment, Score, FeaturedScore
from .serializers import AttachmentSerializer, ScoreSerializer, ScoreLightSerializer



class AttachmentViewSet(viewsets.ModelViewSet):
    queryset = Attachment.objects.all()
    serializer_class = AttachmentSerializer
    parser_classes = (MultiPartParser, FormParser,)

    def perform_create(self, serializer):
        serializer.save(attachment=self.request.data.get('attachment'))


class ScoreViewSetPagination(PageNumberPagination):
    # page_size = 10
    page_size_query_param = 'page_size'
    # max_page_size = 10000


class ScoreFilter(FilterSet):
    is_featured = BooleanFilter(method='my_custom_filter')

    class Meta:
        model = Score
        fields = ('title', 'score_type', 'is_featured')


class ScoreViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = Score.objects.all()
    pagination_class = ScoreViewSetPagination
    filter_backends = (DjangoFilterBackend, OrderingFilter, SearchFilter)
    search_fields = ('title',)
    # filter_fields = ('title', 'score_type')
    filter_class = ScoreFilter

    def get_queryset(self):
        """
        Optionally restricts the returned purchases to a given user,
        by filtering against a `username` query parameter in the URL.
        """
        queryset = self.queryset
        is_featured = self.request.query_params.get('is_featured', None)
        if is_featured is not None:
            ids = FeaturedScore.objects.all().values_list("score__id", flat=True)
            queryset = queryset.filter(id__in=ids)
        return queryset

    def get_serializer_class(self, *args, **kwargs):
        """
        Expose a lighter set of fields when a list is required
        """
        if self.action in ['list']:
            return ScoreLightSerializer
        else:
            return ScoreSerializer
    

class ScoreView(TemplateView):
    """
    """
    template_name = "playground/score.html"