Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django limit query not working in get_queryset

I overwrite get_queryset as below:

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        qs.order_by('-id').all()[:3]
        print(qs)
        print()

        qs2 = CreditsTransaction.objects.all()[:3]
        print(qs2)
        return qs

This is my output:

[2023-04-19 08:53:52 +0000] [1178] [INFO] Booting worker with pid: 1178
<QuerySet [<CreditsTransaction: CreditsTransaction object (623267)>, <CreditsTransaction: CreditsTransaction object (623266)>, <CreditsTransaction: CreditsTransaction object (623265)>, <CreditsTransaction: CreditsTransaction object (623264)>, <CreditsTransaction: CreditsTransaction object (623263)>, '...(remaining elements truncated)...']>

<QuerySet [<CreditsTransaction: CreditsTransaction object (623267)>, <CreditsTransaction: CreditsTransaction object (623266)>, <CreditsTransaction: CreditsTransaction object (623265)>]>

So in qs.order_by('-id').all()[:3] the number of results is not limited to 3. Whereas in CreditsTransaction.objects.all()[:3] it is. I want to know why.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have a logical error in the code. The line qs.order_by('-id').all()[:3] does not get saved back in qs variable. So, you print the original qs.

You need to do qs = qs.order_by('-id').all()[:3] in order to get what you want.

def get_queryset(self, request):
    qs = super().get_queryset(request)
    qs = qs.order_by('-id').all()[:3]
    print(qs)
    print()

    qs2 = CreditsTransaction.objects.all()[:3]
    print(qs2)
    return qs
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading