Home > Mobile >  Duration matching query does not exist
Duration matching query does not exist

Time:07-21

Traceback (most recent call last):


  File "/home/ahmed/SavannahX/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/ahmed/SavannahX/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/ahmed/SavannahX/venv/lib/python3.9/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/home/ahmed/SavannahX/app/views.py", line 1352, in yearly_subscription_plans
    duration = Duration.objects.get(name="yearly")
  File "/home/ahmed/SavannahX/venv/lib/python3.9/site-packages/```

django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/ahmed/SavannahX/venv/lib/python3.9/site-packages/django/db/models/query.py", line 496, in get raise self.model.DoesNotExist(


Exception Type: DoesNotExist at /yearly/subscriptions/
Exception Value: Duration matching query does not exist.

CodePudding user response:

You are using the .get() function but it has not found a matching object. This is the danger of using get, it raises an exception if the object isn't found. The .filter() function by contrast will just return an empty queryset. You can either:

  1. Use the get_object_or_404 function that returns a 404 HTTP response if the object is not found.

    from django.shortcuts import get_object_or_404
    
    duration = get_object_or_404(Duration, pk=pk)
    

    or

  2. Wrap the get() in a try/except wrapper:

    try:
       Duration.objects.get(name="yearly")
    except:
       # do something else, probably return 404...
    

CodePudding user response:

duration = Duration.objects.get(name="yearly")

above code is giving the error as get method raises the "DoesNotExist" if the object is not found and can be handled as below ways

First method

Duration.objects.filter(name="yearly").first()

Second method

from django.shortcuts import get_object_or_404
duration = get_object_or_404(Duration, pk=pk)

Third method

try:
Duration.objects.get(name="yearly")
except:
#please handle the exception here

  • Related