5

I would to have a custom query to show a List of element in my admin django panel.

So, to have this I use a code like this:

class MyAdmin(admin.ModelAdmin):
....
   def get_queryset(self, request):
        return Post.objects.filter(author_type=AuthorType.USER)

This work well but I need also to add a LIMIT for this queryset:

class MyAdmin(admin.ModelAdmin):
....
   def get_queryset(self, request):
        return Post.objects.filter(author_type=AuthorType.USER)[:500]

But when I add the limit clause [:500] I have this error:

Exception Value: Cannot reorder a query once a slice has been taken.

any suggestions?

Moe Far
  • 2,742
  • 2
  • 23
  • 41
Safari
  • 11,437
  • 24
  • 91
  • 191

3 Answers3

2

Django is calling another get_queryset method defined in ChangeList after calling your custom get_queryset method defined in ModelAdmin (see ChangeList source code).

To apply limit in admin correctly, define your own ChangeList:

from django.contrib.admin.views.main import ChangeList

class CustomChangeList(ChangeList):
    def get_queryset(self, request):
        queryset = super(CustomChangeList, self).get_queryset(request)

        return queryset[:5000]

And return this class from ModelAdmin:

@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
    list_display = ['__str__']

    def get_changelist(self, request, **kwargs):
        return CustomChangeList
illagrenan
  • 6,033
  • 2
  • 54
  • 66
0

obviously somewhere is happening ordering after your slice, you should try this:

def get_queryset(self, request):
    qs = super(MyAdmin, self).queryset(request)
    return qs.filter(author_type=AuthorType.USER)[:500]
Safari
  • 11,437
  • 24
  • 91
  • 191
doniyor
  • 36,596
  • 57
  • 175
  • 260
0

You can follow this link, https://stackoverflow.com/a/36476084 @pahaz's answer is more precisely.

First, you need to create your changelist like @illagrenan

from django.contrib.admin.views.main import ChangeList
class CustomChangeList(ChangeList):
    def get_queryset(self, request):
        queryset = super(CustomChangeList, self).get_queryset(request)

    return queryset[:5000]

and then let your modeladmin get this changelist,

class YourModelAdmin(admin.ModelAdmin):
    def get_changelist(self, request, **kwargs):
        return CustomChangeList

I tested it and worked out, hope it can help you.

FLYtheSKY
  • 42
  • 4