Phoenix
Phoenix

Reputation: 4284

How can get last nth item of a query on PostgreSql

Question:

How I can get the last 750 records of a query in the Database level?

Here is What I have tried:

# Get last 750 applications

apps = MyModel.active_objects.filter(
    **query_params
).order_by('-created_at').values_list('id', flat=True)[:750]

This query fetches all records that hit the query_params filter and after that return the last 750 records. So I want to do this work at the database level, like mongoDb aggregate queries. Is it possible?

Thanks.

Upvotes: 1

Views: 72

Answers (1)

Navid Zarepak
Navid Zarepak

Reputation: 4208

Actually that's not how Django works. The limit part is also done in database level.

Django docs - Limiting QuerySets:

Generally, slicing a QuerySet returns a new QuerySet – it doesn’t evaluate the query.

To see what query is actually being run in the database you can simply print the query like this:

apps = MyModel.active_objects.filter(
           **query_params
       ).order_by('-created_at').values_list('id', flat=True)[:750]
print(apps.query)

The result will be something like this:

SELECT * FROM "app_mymodel" WHERE <...> ORDER BY "app_mymodel"."created_at" DESC LIMIT 750

Upvotes: 1

Related Questions