How to specify maximum results for a filter request in Django?

I want to get the first 500 results from a large database that match the given filter query.

I am currently using the following (terribly inefficient) method.

results = Entries.objects.filter(text__icontains="somequery")[0:500] 

But I think this query loads the entire database into memory and then truncates the results. It is terribly slow.

Is there a more elegant way to do this? Thanks!

+7
source share
1 answer

This is the way to do it.

The generated SQL uses LIMIT , so it does not load the entire database into memory and does not chop into python.

Note that you can see what django SQL is django.db.connection.queries using django.db.connection.queries http://docs.djangoproject.com/en/dev/faq/models/#how-can-i-see-the- raw-sql-queries-django-is-running

But a lesser known way is to type queryset.query or call sql = queryset.query.__str__()

 >>> results = Entries.objects.filter(text__icontains="somequery")[0:500] >>> print results.query SELECT ... FROM ... WHERE ... LIKE ... LIMIT 500 
+23
source

All Articles