python.django.performance.upsell-count.use-count-method

profile photo of semgrepsemgrep
Author
9,905
Download Count*

Looks like you need to determine the number of records. Django provides the count() method which is more efficient than .len(). See https://docs.djangoproject.com/en/3.0/ref/models/querysets/

Run Locally

Run in CI

Defintion

rules:
  - id: use-count-method
    message: Looks like you need to determine the number of records. Django provides
      the count() method which is more efficient than .len(). See
      https://docs.djangoproject.com/en/3.0/ref/models/querysets/
    languages:
      - python
    severity: ERROR
    pattern-either:
      - pattern: $X.objects.$FUNC(...).len()
      - pattern: $X.objects.$FUNC(...).$FILTER().len()
      - pattern: $X.objects.$FUNC(...).$FILTER().$UPDATE(...).len()
    metadata:
      category: performance
      technology:
        - django
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]

Examples

upsell-count.py

# ruleid:use-count-method
print(Entry.objects.all().len())
# ruleid:use-count-method
print(Entry.objects.get().filter().len())
# ruleid:use-count-method
print(Entry.objects.filter().filter().len())