Python Forum

Full Version: Django - Catching None in Try/Except
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Essentially, using Django, I've got a next tutorial button that finds the next tutorial by selecting an order value greater than the current tutorial, and choosing the first of the returned values.

If there is *no* next tutorial in the chapter (it will return None), where instead, it will find the next chapter.

    next_video = tutorials.filter(chapter__coursechapter__ordering=current_chapter)\
        .filter(ordering__gt=current_tutorial).first()
    if next_video is None:
        next_video = tutorials.filter(chapter__coursechapter__ordering__gt=current_chapter).filter(ordering=1)\
            .first()
The result is a simple bit of code that allows it to find the next tutorial (or) chapter if None is found, until it runs out of tutorials/chapters to look for. Once it runs out, it will again return None.

My question is if there is a way to catch the second time it returns None and do something else. So when it runs out of tutorials/chapters to loop through it can finish. My thought was a Try/Except - but I wasn't sure how to catch None in an exception?
Just use some kind of switch - on/off. When the first time you get None set it to on or True or whatever and when the next time gets None check the value and take some actions. After that, you can set it back to off/False