Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an object exists

I need to check if Model.objects.filter(...) turned up anything, but do not need to insert anything. My code so far is:

user_pass = log_in(request.POST)  # form class if user_pass.is_valid():     cleaned_info = user_pass.cleaned_data     user_object = User.objects.filter(email = cleaned_info['username']) 
like image 835
sinθ Avatar asked Jul 30 '12 01:07

sinθ


People also ask

How do I check if an object exists?

Method 1: Using the typeof operator The typeof operator returns the type of the variable on which it is called as a string. The return string for any object that does not exist is “undefined”. This can be used to check if an object exists or not, as a non-existing object will always return “undefined”.

How do you check if an object contains a value?

You can use Object. values(): The Object. values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

How do I check if an object contains a property?

We can check if a property exists in the object by checking if property !== undefined . In this example, it would return true because the name property does exist in the developer object.


2 Answers

I think the easiest from a logical and efficiency point of view is using the queryset's exists() function, documented here:

https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.exists

So in your example above I would simply write:

if User.objects.filter(email = cleaned_info['username']).exists():     # at least one object satisfying query exists else:     # no object satisfying query exists 
like image 59
mpaf Avatar answered Sep 30 '22 12:09

mpaf


Since filter returns a QuerySet, you can use count to check how many results were returned. This is assuming you don't actually need the results.

num_results = User.objects.filter(email = cleaned_info['username']).count() 

After looking at the documentation though, it's better to just call len on your filter if you are planning on using the results later, as you'll only be making one sql query:

A count() call performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result (unless you need to load the objects into memory anyway, in which case len() will be faster).

num_results = len(user_object) 
like image 42
joneshf Avatar answered Sep 30 '22 10:09

joneshf