115

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)) {
    // True condition
    }
else {
    // False condition
    }
Mauro Baraldi
  • 6,346
  • 2
  • 32
  • 43
Hulk
  • 32,860
  • 62
  • 144
  • 215
  • Possible duplicate of [what is the right way to validate if an object exists in a django view without returning 404?](http://stackoverflow.com/questions/639836/what-is-the-right-way-to-validate-if-an-object-exists-in-a-django-view-without-r) – Wtower Apr 17 '17 at 19:40

5 Answers5

235

As of 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")
Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129
sdornan
  • 2,805
  • 2
  • 15
  • 7
119

You can 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 perform the query in the simplest and fastest way possible, but it does execute nearly the same query as a normal QuerySet query.

Older versions: (<1.2)

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, an ObjectDoesNotExist exception is raised:

from django.core.exceptions import ObjectDoesNotExist
try:
    sc = scorm.objects.get(pk=someid)
except ObjectDoesNotExist:
    print ...
Neuron
  • 5,141
  • 5
  • 38
  • 59
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

Django provides a method called exists() to check if results exists for our query. exists() method return 'True' or 'False'

Class Company(models.Model):
      name = models.CharField(max_length=100)
      year_established = models.DateField()

Class Car(models.Model):
     name = models.CharField(max_length=100)
     company = models.ForeignKey(Company,related_name='car_company',on_delete=models.CASCADE)

following are the queries with exists() method

1. Car.objects.filter(name='tesla').exists()  
2. Company.objects.filter(year_established='date').exists()

using exists in related field - here foreign key

  1. Car.objects.filter(company__name='tesla').exists()

you can give any filter available and use exists() method

0

this worked for me!

if some_queryset.objects.all().exists(): print("this table is not empty")

0

len(queryset) also works.

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

if len(sc):
    ....
SuperNova
  • 25,512
  • 7
  • 93
  • 64
  • 1
    you should not use length on a queryset. `.count()` is better but less performant than `.exists()`. Though `.count()` can be useful if you want to retrieve the number of elements in the query – Léo Chaz Maltrait May 18 '22 at 10:11