Check if an object exists

sinθ picture sinθ · Jul 30, 2012 · Viewed 113.1k times · Source

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'])

Answer

mpaf picture mpaf · Feb 13, 2014

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