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

StackOverflow https://stackoverflow.com/questions/639836

  •  11-07-2019
  •  | 
  •  

Question

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:
Was it helpful?

Solution

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

OTHER TIPS

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.

listing = RealEstateListing.objects.filter(slug_url=slug).first() 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top