简体   繁体   中英

How to disable sorting by primary key in Django Admin?

Django admin sorts by primary key in addition to sorting fields specified in the model "ordering" record, thus, making it necessary to have composite indexes on a model just to allow sorting, which can be very prohibitive on a moderate amount of data(~5 000 000 records)

This is a default behaviour of Django Admin selecting query

SELECT * FROM `book` ORDER BY `book`.`added_at` ASC, `book`.`book_id` DESC LIMIT 100

I want to achieve the following behaviour

 SELECT * FROM `book` ORDER BY `book`.`added_at` ASC LIMIT 100

I guess I'm a bit late in here, but this may help someone in the future.

Django enforces a -pk ordering in order to be sure resulting queryset is deterministic - see here and here for example.

If you really want to disable it you can create your own ChangeList subclass and override get_ordering method like:

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

class NoPkDescOrderedChangeList(ChangeList):
    def get_ordering(self, request, queryset):
        rv = super().get_ordering(request, queryset)
        rv = list(rv)
        rv.remove('-pk') if '-pk' in rv else None
        return tuple(rv)

class YourExistingAdmin(admin.ModelAdmin):
    def get_changelist(self, request):
        return NoPkDescOrderedChangeList

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