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'])
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!
...
I think the easiest from a logical and efficiency point of view is using the queryset's exists() function, documented here:
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
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
You can use:
try:
# get your models
except ObjectDoesNotExist:
# do something
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.
Source: Stackoverflow.com