jieter / django-tables2

django-tables2 - An app for creating HTML tables
https://django-tables2.readthedocs.io/en/latest/
Other
1.9k stars 429 forks source link

TableQuerysetData.__len__ calls len() on a QuerySet instead of using count() #833

Open ercpe opened 2 years ago

ercpe commented 2 years ago

Hi,

the __len__ implementation of TableQuerysetData class only checks for the presence of the paginator to determine to use .count() over len(): https://github.com/jieter/django-tables2/blob/master/django_tables2/data.py#L150 Unfortunately, __len__ of a QuerySet is implemented to fetch all records and using len() on the result list: https://github.com/django/django/blob/main/django/db/models/query.py#L302

This can be a really expensive operation. I suggest to change the condition to

if hasattr(self.table, "paginator") or isinstance(self.data, QuerySet):

to utilize the much faster .count() query in case of a QuerySet.

tuky commented 2 years ago

what would be the benefit? without pagination, the whole queryset will be listed anyway, right? so the current code version is already optimized and saves the count() call.