如何在Django中为过滤器查询指定最大结果?

时间:2022-03-28 02:16:51

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

我想从与给定过滤器查询匹配的大型数据库中检索前500个结果。

At the moment I'm using the following (terribly inefficient) method..

目前我正在使用以下(非常低效)的方法..

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

But I think this query loads the entire database in memory and then truncates the results. It's terribly slow.

但我认为此查询会将整个数据库加载到内存中,然后截断结果。这非常慢。

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

有没有更优雅的方式来做到这一点?谢谢!

1 个解决方案

#1


24  

That's the way to do it.

这是做到这一点的方法。

The SQL generated uses LIMIT so it's not loading the entire database into memory and being python sliced.

生成的SQL使用LIMIT,因此它不会将整个数据库加载到内存中并进行python切片。

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

请注意,您可以使用django.db.connection.queries http://docs.djangoproject.com/en/dev/faq/models/#how-can-i-see-the-raw-查看SQL django正在编写的内容。 SQL查询,Django的是运行的

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

但是一个鲜为人知的技巧是打印queryset.query或调用sql = queryset.query .__ str __()

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

#1


24  

That's the way to do it.

这是做到这一点的方法。

The SQL generated uses LIMIT so it's not loading the entire database into memory and being python sliced.

生成的SQL使用LIMIT,因此它不会将整个数据库加载到内存中并进行python切片。

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

请注意,您可以使用django.db.connection.queries http://docs.djangoproject.com/en/dev/faq/models/#how-can-i-see-the-raw-查看SQL django正在编写的内容。 SQL查询,Django的是运行的

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

但是一个鲜为人知的技巧是打印queryset.query或调用sql = queryset.query .__ str __()

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