78👍
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)
197👍
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
- [Django]-POST jQuery array to Django
- [Django]-How to put comments in Django templates?
- [Django]-Django gunicorn sock file not created by wsgi
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
- [Django]-Django F() division – How to avoid rounding off
- [Django]-How do you skip a unit test in Django?
- [Django]-What is the max size of 'max_length' in Django?
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.
- [Django]-TypeError: data.forEach is not a function
- [Django]-Django development IDE
- [Django]-Pass extra arguments to Serializer Class in Django Rest Framework
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!
...
- [Django]-Django.db.utils.ProgrammingError: relation "bot_trade" does not exist
- [Django]-How to understand lazy function in Django utils functional module
- [Django]-Can I access constants in settings.py from templates in Django?
- [Django]-Change a form value before validation in Django form
- [Django]-Django: How to format a DateField's date representation?
- [Django]-Exclude fields in Django admin for users other than superuser