97

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'])
2
  • 1
    i don't understand what you are trying to do. Are you trying to check if a user already exists in order to raise an error? Why do you need to check that? And why are you doing this in a "form view"? Try to answer this question to see if we can help you better... Add a context to your problem, not just the question you have in mind. Sometimes the problem you think you have is not the real problem so your question you asked is not the correct... Jul 30, 2012 at 3:07
  • 2

6 Answers 6

201

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
2
  • @sinθ seems like a more apt accepted answer
    – Anupam
    Feb 26, 2021 at 9:34
  • this approach scales well
    – kta
    Nov 15, 2023 at 0:06
79

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)
2
10

If the user exists you can get the user in user_object else user_object will be None.

try:
    user_object = User.objects.get(email = cleaned_info['username'])
except User.DoesNotExist:
    user_object = None
if user_object:
    # user exist
    pass
else:
    # user does not exist
    pass
7

the boolean value of an empty QuerySet is also False, so you could also just do...

...
if not user_object:
   do insert or whatever etc.
1
  • 4
    this is not very efficient as it will evaluate the query, and when objects do exists it will load them into memory
    – mpaf
    Feb 13, 2014 at 9:50
6

You can also use get_object_or_404(), it will raise a Http404 if the object wasn't found:

user_pass = log_in(request.POST) #form class
if user_pass.is_valid():
    cleaned_info = user_pass.cleaned_data
    user_object = get_object_or_404(User, email=cleaned_info['username'])
    # User object found, you are good to go!
    ...
4

You can use:

try:
   # get your models
except ObjectDoesNotExist:
   # do something

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.