Use count() :
sc=scorm.objects.filter(Header__id=qp.id) if sc.count() > 0: ...
The advantage over, for example, len() is that the QuerySet has not yet been evaluated:
count() does SELECT COUNT(*) behind the scenes, so you should always use count() , not load the entire record into Python objects and call len() as a result.
With that in mind, when QuerySets are evaluated , it's worth a read.
If you use get() , for example. scorm.objects.get(pk=someid) and the object does not exist, an ObjectDoesNotExist exception is thrown:
from django.core.exceptions import ObjectDoesNotExist try: sc = scorm.objects.get(pk=someid) except ObjectDoesNotExist: print ...
Update: you can also use exists() :
if scorm.objects.filter(Header__id=qp.id).exists(): ....
Returns True if the QuerySet contains any results, and False if not. This tries to execute the query in the simplest and fastest way , but it performs almost the same query as a regular QuerySet query.
Felix Kling Apr 22 2018-10-22T00: 00Z
source share