Jaime38130
Jaime38130

Reputation: 165

How to catch an empty query exception with Django

I'm after an elegant and efficient approach.

I am doing a query to a model that has a chance to return an empty queryset and if that happens I must do a query with other parameters that will work for sure.

It would be really nice if I could put the query inside a simple try except but it doesn't catch like so.

What's holding me back from using .exists() is that it feels like I'm doing the query to the database two times. One to check the existence and the other to really get the object.

Upvotes: 1

Views: 1000

Answers (1)

Egor Wexler
Egor Wexler

Reputation: 1944

To avoid double-query you can do:

objects = models.MyModel.objects.filter(key=value)

if not objects:
    objects = models.MyModel.objects.filter(another_key=another_value)

In this case bool(objects) does not evaluate query for existance unlike using exists or len()

Per documentation:

Additionally, if a some_queryset has not yet been evaluated, but you know that it will be at some point, then using some_queryset.exists() will do more overall work (one query for the existence check plus an extra one to later retrieve the results) than using bool(some_queryset), which retrieves the results and then checks if any were returned.

https://docs.djangoproject.com/en/4.0/ref/models/querysets/#django.db.models.query.QuerySet.exists

Upvotes: 2

Related Questions