50
Update:
As mentioned in more recent answers, since Django 1.2 you can use the exists()
method instead (link).
Original Answer:
Dontβ use len() on the result, you should use People.objects.filter(Name='Fred').count()
. According to the django documentation,
count() 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).
source: Django docs
- [Django]-Django url pattern β string parameter
- [Django]-Django: manage.py does not print stack trace for errors
- [Django]-Why is Django throwing error "DisallowedHost at /"?
11
You could use count()
For example:
People.objects.filter(Name='Fred').count()
If the Name column is unique then you could do:
try:
person = People.objects.get(Name='Fred')
except (People.DoesNotExist):
# Do something else...
You could also use get_object_or_404()
For example:
from django.shortcuts import get_object_or_404
get_object_or_404(People, Name='Fred')
- [Django]-(13: Permission denied) while connecting to upstream:[nginx]
- [Django]-Where does pip install its packages?
- [Django]-AttributeError: 'module' object has no attribute 'tests'
8
As of Django 1.2 you could use .exists()
on a QuerySet, but in previous versions you may enjoy very effective trick described in this ticket.
- [Django]-Django Footer and header on each page with {% extends }
- [Django]-Rendering a template variable as HTML
- [Django]-Django: reverse accessors for foreign keys clashing
0
For the sake of explicitness: .exists()
is called on a QuerySet and not an object.
This works:
>>> User.objects.filter(pk=12).exists()
True
This does not work:
>>> User.objects.get(pk=12).exists()
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'User' object has no attribute 'exists'
- [Django]-How to add multiple objects to ManyToMany relationship at once in Django ?
- [Django]-Django cannot import name x
- [Django]-How can I get the full/absolute URL (with domain) in Django?