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

Viewed 93067

I need to verify if an object exists and return the object, then based on that perform actions. What's the right way to do it without returning a 404?

try:
    listing = RealEstateListing.objects.get(slug_url = slug)
except:
    listing = None

if listing:
4 Answers

I would not use the 404 wrapper if you aren't given a 404. That is misuse of intent. Just catch the DoesNotExist, instead.

try:
    listing = RealEstateListing.objects.get(slug_url=slug)
except RealEstateListing.DoesNotExist:
    listing = None

I would do it as simple as follows:

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

I don't see a need for try/catch. If there are potentially several objects in the result, then use first() as shown by user Henrik Heino

Related