开发者

For Django models, is there a shortcut for seeing if a record exists?

Say I have a table People, is there a way to just quickly check if a People object exists with开发者_StackOverflow a name of 'Fred'? I know I can query

People.objects.filter(Name='Fred')

and then check the length of the returned result, but is there a way to do it in a more elegant way?


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


An exists() method in the QuerySet API is available since Django 1.2.


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


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.


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'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜