Home > Back-end >  Try and except for Query set
Try and except for Query set

Time:04-11

I want to do something similar to try and except for single object .. in my situation I got a Query set and I want to do something like :

try:
    qs = model.objects.filter(id=1)
except qs.DoesNotExist:
    raise Http_404()

How can I do that ?

CodePudding user response:

You can use the get_list_or_404(…) function [Django-doc] for this:

from django.shortcuts import get_list_or_404

qs = get_list_or_404(model, id=1)

but since you are filtering on a primary key, it makes not much sense to use .filter(…) [Django-doc] here, you can retrieve the single Model object with get_object_or_404(…) [Django-doc]:

from django.shortcuts import get_object_or_404

obj = get_object_or_404(model, id=1)

CodePudding user response:

There is no way to caught an exception since none is raisen.

Why don't you try something like that?

qs = model.objects.filter(id=1)

if len(qs) == 0:
    raise Http_404()

Or, if you are not using qs after that, the more efficient if qs.count() == 0:.

CodePudding user response:

views.py

@api_view(['GET'])
def getObjList(request):
    if request.method == 'GET':
       serialized_data = 
       serializers.FstObjSerializer(models.FstObjModel.objects.filter(id=2), 
       many=True)
       if serialized_data.data:
           return Response(serialized_data, status=status.HTTP_200_OK)
       else:
           return Response({"error":"any message you want"}, 
           status=status.HTTP_400_BAD_REQUEST)

serializers:

 class FstObjSerializer(serializers.ModelSerializer):
 class Meta:
     model = models.FstObjModel
     fields = '__all__'

You can do the above

  • Related