Skip to content

Commit

Permalink
Add PromptRetrieveUpdateDestroyAPIView
Browse files Browse the repository at this point in the history
  • Loading branch information
danielzeljko committed Mar 9, 2024
1 parent a965943 commit 52cae2a
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
13 changes: 13 additions & 0 deletions langcorrect/prompts/api/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from django.urls import path

from langcorrect.prompts.api.views import PromptListCreateAPIView
from langcorrect.prompts.api.views import PromptRetrieveUpdateDestroyAPIView

urlpatterns = [
path("", view=PromptListCreateAPIView.as_view(), name="prompt-list-create"),
path(
"<str:slug>/",
view=PromptRetrieveUpdateDestroyAPIView.as_view(),
name="prompt-detail",
),
]
53 changes: 53 additions & 0 deletions langcorrect/prompts/api/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
from rest_framework import generics

from config.api.permissions import IsOwnerOrStaff
from langcorrect.prompts.api.serializers import PromptSerializer
from langcorrect.prompts.models import Prompt


class PromptListCreateAPIView(generics.ListCreateAPIView):
queryset = Prompt.objects.all()
serializer_class = PromptSerializer

def get_queryset(self):
queryset = self.queryset.select_related(
"user",
"language",
"challenge",
).prefetch_related("tags")

search = self.request.query_params.get("search")
langs = self.request.query_params.get("langs")

if search:
queryset = queryset.filter(content__icontains=search)

if langs:
codes = langs.split(",")
queryset = queryset.filter(language__code__in=codes)

return queryset

def perform_create(self, serializer):
serializer.save(user=self.request.user)


class PromptRetrieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):
queryset = Prompt.objects.all()
serializer_class = PromptSerializer
lookup_field = "slug"
permission_classes = [IsOwnerOrStaff]

def get_queryset(self):
return self.queryset.select_related(
"user",
"language",
"challenge",
).prefetch_related("tags")

def perform_update(self, serializer):
updates = {}
language = serializer.validated_data.get("lang_code")
if language:
updates["language"] = language
serializer.save(user=self.request.user, **updates)

0 comments on commit 52cae2a

Please sign in to comment.