Junior — Middle
Have I used the exists method in Django to check for object existence?.
sobes.tech AI
Answer from AI
Yes, in Django, the exists() method is often used to check for the existence of objects in the database. It is applied to a QuerySet and returns a boolean value — True if objects matching the filter exist, and False otherwise.
Example:
from myapp.models import Product
# Check if there are products with a price greater than 100
if Product.objects.filter(price__gt=100).exists():
print("There are expensive products")
else:
print("No expensive products")
The exists() method is efficient because it executes a SQL query with SELECT 1 and a LIMIT 1 constraint, which is faster than retrieving all objects.