Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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: 
like image 629
Rasiel Avatar asked Mar 12 '09 18:03

Rasiel


People also ask

How do I check if a class object exists?

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.

Which can be used to retrieve an object directly instead of a Queryset?

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.

Is not exist Django?

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 .


2 Answers

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.

like image 129
zzart Avatar answered Oct 13 '22 22:10

zzart


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 
like image 29
ironfroggy Avatar answered Oct 13 '22 23:10

ironfroggy