119π
You can use exists()
:
if scorm.objects.filter(Header__id=qp.id).exists():
....
Returns
True
if the QuerySet contains any results, andFalse
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 aSELECT COUNT(*)
behind the scenes, so you should always usecount()
rather than loading all of the record into Python objects and callinglen()
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 ...
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")
- [Django]-How to merge consecutive database migrations in django 1.9+?
- [Django]-Python Django Gmail SMTP setup
- [Django]-Django index page best/most common practice
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
Car.objects.filter(company__name='tesla').exists()
you can give any filter available and use exists() method
- [Django]-Why won't Django use IPython?
- [Django]-On Heroku, is there danger in a Django syncdb / South migrate after the instance has already restarted with changed model code?
- [Django]-Django ModelForm: What is save(commit=False) used for?
0π
this worked for me!
if some_queryset.objects.all().exists():
print("this table is not empty")
- [Django]-Django models: Only permit one entry in a model?
- [Django]-Django render_to_string missing information
- [Django]-How to get superuser details in Django?
0π
len(queryset)
also works.
sc = scorm.objects.filter(Header__id=qp.id)
if len(sc):
....
- [Django]-Django queries β id vs pk
- [Django]-What is the SQL ''LIKE" equivalent on Django ORM queries?
- [Django]-How to filter empty or NULL names in a QuerySet?