python - count() on filter chains in Django -
when chaining filters in django, efficient way of counting resulting records individual filter? without running filter twice is.
i.e.
results = my_model.objects.all() filter in my_filters: results = results.filter(filter.get_filter_string()) individual_num_records_affected = my_model.objects.filter(filter.get_filter_string())
since need number of results @ each step, more efficient use .count()
on querysets.
from querysets
documentation:
note: if need determine number of records in set (and don’t need actual objects), it’s much more efficient handle count @ database level using sql’s
select count(*)
. django providescount()
method precisely reason.
you should not use .len()
load of record python objects , calls len()
on result don't need. need number of records , .count()
better option.
also, remember querysets evaluated lazy.
internally, queryset can constructed, filtered, sliced, , passed around without hitting database. no database activity occurs until evaluate queryset.
so, until try use results of queryset, queryset not evaluated i.e. no database hit occur.
the statement results = results.filter(filter.get_filter_string())
not hit database until try use results
. you can .filter()
on queryset multiple times until don't use it, there no database hit.
Comments
Post a Comment