Matt Parrilla
Matt Parrilla

Reputation: 3221

Django query efficiency

If I've got:

class Address(models.Model):
    state = models.CharField(max_length=2)
    city = models.CharField(max_length=50)
    street = models.CharField(max_length=50)

and a large dataset, which is more efficient:

Address.objects.filter(state__exact='xx').filter(city__exact='somewhere').filter(street__exact='some street')

OR

Address.objects.filter(state__exact='xx', city__exact='somewhere', street__exact = 'some_street')

Upvotes: 1

Views: 503

Answers (2)

Matt Parrilla
Matt Parrilla

Reputation: 3221

The latter query takes roughly 1/3 of the time of the former in my test.

Using a model with 11,695 entries.

class TimeZip(models.Model):
    zipcode = models.SlugField(max_length=5)
    timezone = models.IntegerField(default=-5)
    state = models.CharField(max_length=2)
    city = models.CharField(max_length=50)

and then testing:

Timer("TimeZip.objects.filter(state__iexact='xx')\
     .filter(city__iexact='somewhere')\
     .filter(timezone__iexact='est')",
     "from shows.models import TimeZip"
).timeit(1000)

resulted in a time of 1.2074651718139648 seconds, while

Timer("TimeZip.objects.filter(state__iexact='xx',
     city__iexact='somewhere',
     timezone__iexact='est')",
     "from shows.models import TimeZip"
).timeit(1000)

resulted in a time of 0.4363691806793213 seconds.

Quite a significant difference!

Upvotes: 2

Kekoa
Kekoa

Reputation: 28250

The same QuerySet should be constructed, so it should be the same. You might have tiny differences because of 3 method calls instead of 1, but as far as database query time, you will see no difference.

If there is a difference, there could be a bug somewhere.

Upvotes: 4

Related Questions