I'm trying to get data that is related to the request.user but i'm doing something wrong.
serializers.py
class SchoolSerializerList(serializers.ModelSerializer):
class Meta:
model = School
fields = ('name', 'zone', 'city', 'subCity', 'abbr',
'woreda', 'Schooltype', 'schoolemail', 'schoolphone', 'created_date')
views.py
class MySchoolsView(generics.ListAPIView):
permission_classes = [IsSchoolOwner, ]
serializer_class = SchoolSerializerList
def get_queryset(request):
try:
queryset = School.objects.filter(owner=request.user)
except ObjectDoesNotExist:
return Response({"error": "Nothing found."})
return queryset
the owner field in the school model is a foreignkey to the user i wanted to check if the current user has any schools by trying to match request.user with School.owner but this returns an attribute error saying
'MySchoolsView' object has no attribute 'user'
CodePudding user response:
The first and only parameter of get_queryset
is self
, not request
. You can access the request object with self.ruquest
, so:
class MySchoolsView(generics.ListAPIView):
permission_classes = [IsSchoolOwner, ]
serializer_class = SchoolSerializerList
def get_queryset(self):
return School.objects.filter(owner=self.request.user)
Your get_queryset
can also not return a Response
. You can raise a Http404
error:
from django.http import Http404
class MySchoolsView(generics.ListAPIView):
permission_classes = [IsSchoolOwner, ]
serializer_class = SchoolSerializerList
def get_queryset(self):
qs = School.objects.filter(owner=self.request.user)
if not qs:
raise Http404('No schools found')
return qs