Polished study_groups list view to only show study_groups which are the same course as the user requesting

This commit is contained in:
Keannu Bernasol 2023-06-27 22:57:37 +08:00
parent 8c337295e2
commit 11d6887af8
3 changed files with 35 additions and 1 deletions

View file

@ -7,5 +7,6 @@ urlpatterns = [
path('courses/', include('courses.urls')),
path('year_levels/', include('year_levels.urls')),
path('semesters/', include('semesters.urls')),
path('subjects/', include('subjects.urls'))
path('subjects/', include('subjects.urls')),
path('study_groups/', include('study_groups.urls'))
]

View file

@ -0,0 +1,7 @@
from django.urls import include, path
from .views import StudyGroupListView, StudyGroupMembershipViewSet
urlpatterns = [
path('', StudyGroupListView.as_view()),
path('membership/', StudyGroupMembershipViewSet.as_view()),
]

View file

@ -1,14 +1,40 @@
from django.shortcuts import render
from rest_framework import generics
from rest_framework.exceptions import PermissionDenied
from rest_framework.permissions import IsAuthenticated
from .serializers import StudyGroupSerializer
from .models import StudyGroup
from courses.models import SubjectCourse
# Create your views here.
class StudyGroupListView(generics.ListAPIView):
permission_classes = [IsAuthenticated]
serializer_class = StudyGroupSerializer
queryset = StudyGroup.objects.all()
def get_queryset(self):
user = self.request.user
if not user.is_student:
raise PermissionDenied(
"You must be a student to view study groups"
)
# Get the user's course
user_course = user.course
print(user_course)
# Get subject ids related to the user's course through SubjectCourse
subject_ids = SubjectCourse.objects.filter(
course=user_course
).values_list('subject', flat=True)
print(subject_ids)
# Now fetch the StudyGroups with the subjects from the obtained subject_ids
studygroups = StudyGroup.objects.filter(subject_id__in=subject_ids)
return studygroups
class StudyGroupMembershipViewSet(generics.ListAPIView):
serializer_class = StudyGroupSerializer