1

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.

1
  • 1
    That is doing it at the database level. It does not fetch all records. Commented Nov 21, 2019 at 19:21

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.