简体   繁体   中英

how can i use try and except while getting model objects?

I have to use a try and except block with the following code, as I am trying to get a model class object but in case if database is empty so for that I need to use try and except.

if(txStatus=='SUCCESS'):
    order=Order.objects.get(id=id)    #NEED TRY ACCEPT BLOCK FOR THIS
    URL = payment_collection_webhook_url 
    request_data ={}          
    json_data = json.dumps(request_data)
    requests.post(url = URL, data = json_data)
    return Response(status=status.HTTP_200_OK)

It is as simple as this:

try:
    order = Order.objects.get(id=order_id)
except Order.DoesNotExist:
    # Exception thrown when the .get() function does not find any item.
    pass  # Handle the exception here. 

You can find more information about DoesNotExist exception here .

try..except..else..finally block works like this:

try:
    order=Order.objects.get(id=id)
except ObjectDoesNotExist(or MultipleObjectsReturned in case it returns more 
than 1 queryset or instance):
    ...Handle the exception, Write any code you want
else:
    ...This gets called if there is no exception or error, means it will 
    execute right after try statement if there's no error, so if you want 
    something more to happen only if the code doesn't throw an error, you can 
    write it here
finally:
    ...This gets executed no matter what in any case, means if there's 
    something you want to execute regardless of whether it throws an 
    exception or not, you write it here.

@Hagyn is correct, but in Django there is another way to do that:

Something like this:

orders = Order.objects.filter(id=order_id)
if orders.exists():
    order = orders.last()
else:
    # do rest of the things

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM