Rhubarb Rhubarb - 1 year ago 73
Python Question

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

Say I have a table

, is there a way to just quickly check if a
object exists with a name of
? I know I can query


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

Answer Source


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download