简体   繁体   中英

Custom get_queryset with LIMIT for django admin panel

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?

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

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]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM