Junior — Middle
How can you determine the total number of objects obtained using the QuerySet method?
sobes.tech AI
Answer from AI
To determine the total number of objects obtained using the QuerySet method in Django, you can use the .count() method. It executes the SQL query SELECT COUNT(*) and returns the number of records matching the filter.
Example:
from myapp.models import Product
products = Product.objects.filter(category='books')
total = products.count()
print(f"Total books: {total}")
Important: if you simply call len(products), Django will first load all objects into memory, which is inefficient with large data sets. The .count() method is more optimal as it counts records at the database level.