Dart
Dart

Reputation: 41

django Model.objects.filter(feildname = 'some_column') vs Model.objects.all().filter(feildname = 'some_column') which one performs better

I am trying to see which of these will perform better

  1. queryset = Model.objects.filter(feildname = 'some_column')

  2. queryset = Model.objects.all().filter(feildname = 'some_column')

Upvotes: 0

Views: 344

Answers (2)

Andy
Andy

Reputation: 684

They are the same things if you haven't defined your own manager. We can create our own BaseManager and override all() method. For ex.:

from django.db import models

class BaseManager(models.Manager):
    def all(self):
        return super().get_queryset().filter(is_active=True)

class SomeModel(models.Model):
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = BaseManager()

And now SomeModel.objects.all().filter(fieldname='some_column') - filtering objects with is_active=True, in other case SomeModel.objects.filter(fieldname='some_column') - filtering all objects, doesn't matter what value has is_active field.

Upvotes: 1

stefanw
stefanw

Reputation: 10570

It becomes the same SQL query underneath, so there is no difference.

Also a database query will take much longer than any Django queryset construction, so if you want to improve speed look at the generated SQL (e.g. with django-debug-toolbar).

Upvotes: 1

Related Questions