What is the right way to validate if an object exists in a django view without returning 404?

You can also do:

if not RealEstateListing.objects.filter(slug_url=slug).exists():
    # do stuff...

Sometimes it’s more clear to use try: except: block and other times one-liner exists() makes the code looking clearer… all depends on your application logic.

Leave a Comment