whoisearth
whoisearth

Reputation: 4170

django - class view 404 if no result

I have the following class-based view -

class DeployFilterView(generics.ListAPIView):
    serializer_class = DefinitionSerializer

    def get_queryset(self):
        jobname = self.request.GET.get('jobname')
        if jobname.count("\\") == 1:
            jobname = jobname.replace("\\", "")
            queryset = Jobmst.objects.db_manager('Admiral').filter(jobmst_name=jobname).exclude(jobmst_prntname__isnull=True, jobmst_dirty='X')
        else:
            parent, job = jobname.rsplit('\\', 1)
            queryset = Jobmst.objects.db_manager('Admiral').filter(jobmst_prntname=parent, jobmst_name=job).exclude(jobmst_dirty='X')          

        return queryset

I want to have it return a 404 response if either queryset returns no information how do I go about chaining that in?

I'm using Django Rest Framework. Right now if I call a URL and there's no data it passes a 200 OK which I don't want. Below is what I'm trying -

class DeployFilterView(generics.ListAPIView):
    serializer_class = DefinitionSerializer

    def get_queryset(self):
        jobname = self.request.GET.get('jobname')
        if jobname.count("\\") == 1:
            jobname = jobname.replace("\\", "")
            queryset = Jobmst.objects.db_manager('Admiral').filter(jobmst_name=jobname).exclude(jobmst_prntname__isnull=True, jobmst_dirty='X')
        else:
            parent, job = jobname.rsplit('\\', 1)
            queryset = Jobmst.objects.db_manager('Admiral').filter(jobmst_prntname=parent, jobmst_name=job).exclude(jobmst_dirty='X')
        try:
            if queryset == True:
                return queryset
            else:
                raise exceptions.DoesNotExist

But it fails on saying my indenting is wrong but I don't see how it is.

Upvotes: 0

Views: 1656

Answers (1)

rbonick
rbonick

Reputation: 245

It's likely throwing an issue because you have no except block. You don't need to keep the try block; since you're just doing an if/else statement.

Also, your if queryset == True: is unnecessary, you can just do if queryset:.

Try something like:

from django.http import Http404

# The rest of your code here...

if queryset:
    return queryset
else:
    raise Http404

For more information you can check out django's documentation on returning 404 errors.

Upvotes: 5

Related Questions