views:

136

answers:

1

In django how to check whether any entry exists for a query

       sc=scorm.objects.filter(Header__id=qp.id)

This was how it was done in php

     if(mysql_num_rows($resultn))
     {
      }
      else
      {

       }
+2  A: 

Use count():

sc=scorm.objects.filter(Header__id=qp.id)

if sc.count() > 0:
   ...

The advantage over e.g. len() is, that the QuerySet is not yet evaluated:

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.

Having this in mind, When QuerySets are evaluated can be worth reading.


If you use get(), e.g. scorm.objects.get(pk=someid), and the object does not exists, a DoesNotExist exception is raised:

from django.core.exceptions import ObjectDoesNotExist
try:
    sc = scorm.objects.get(pk=someid)
except ObjectDoesNotExist:
    print ...
Felix Kling
Thanks much.....................
Hulk
`if scorm.objects.filter(Header__id=qp.id).exists()`
Alex Lebedev
@Alex Lebedev: Yes, this method will be available in Django 1.2. Thank you.
Felix Kling