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

DjangoDjango Views

Django Problem Overview


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:

Django Solutions


Solution 1 - Django

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.

Solution 2 - Django

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

Solution 3 - Django

listing = RealEstateListing.objects.filter(slug_url=slug).first() 

Solution 4 - Django

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRasielView Question on Stackoverflow
Solution 1 - DjangozzartView Answer on Stackoverflow
Solution 2 - DjangoironfroggyView Answer on Stackoverflow
Solution 3 - DjangoHenrik HeinoView Answer on Stackoverflow
Solution 4 - DjangoGreg HolstView Answer on Stackoverflow