Junior — Middle
Which QuerySet functions trigger SQL queries to the database?
sobes.tech AI
Answer from AI
In Django, a QuerySet is lazy — the SQL query to the database is executed only when the data is actually needed. Functions and operations that trigger the execution of the query include:
- Iterating over the QuerySet (e.g., a
forloop) - Calling methods that return a list or a single object:
list(),get(),first(),last() - Aggregation methods:
count(),exists(),aggregate() - Conversion to other structures:
values(),values_list() - Forced caching:
len()
Example:
qs = MyModel.objects.filter(active=True) # query not yet executed
count = qs.count() # SQL COUNT query executed here
for obj in qs: # SELECT executed here
print(obj)