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:
Using isinstance() function, we can test whether an object/variable is an instance of the specified type or class such as int or list. In the case of inheritance, we can checks if the specified class is the parent class of an object.
Retrieving Single Objects from QuerySets We can do this using the get() method. The get() returns the single object directly. Let's see the following example. As we can see in both examples, we get the single object not a queryset of a single object.
ObjectDoesNotExist and DoesNotExistDjango provides a DoesNotExist exception as an attribute of each model class to identify the class of object that could not be found and to allow you to catch a particular model class with try/except .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With