Django validation for any exists for request

In django, how to check if there is any entry for a request

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

So it was done in php

 if(mysql_num_rows($resultn)) { // True condition } else { // False condition } 
+51
python django django-views
Apr 22 2018-10-22T00:
source share
2 answers

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.

+46
Apr 22 2018-10-22T00:
source share
— -

As in Django 1.2, you can use exists() :

https://docs.djangoproject.com/en/dev/ref/models/querysets/#exists

 if some_queryset.filter(pk=entity_id).exists(): print("Entry contained in queryset") 
+108
Feb 01 2018-12-12T00:
source share



All Articles