-
-
Save quevon24/a089b761c2f8143719a59791bed5cfab to your computer and use it in GitHub Desktop.
Django Admin Natural Sort QuerySet Example (answer to https://stackoverflow.com/questions/50689359/django-1-11-natural-sort-queryset/59220344#59220344)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.contrib.admin import ModelAdmin, register, SimpleListFilter | |
from django.db.models.functions import Length, StrIndex, Substr, NullIf, Coalesce | |
from django.db.models import Value as V | |
from .models import Item | |
class AlphanumericSignatureFilter(SimpleListFilter): | |
title = 'Signature (alphanumeric)' | |
parameter_name = 'signature_alphanumeric' | |
def lookups(self, request, model_admin): | |
return ( | |
('signature', 'Signature (alphanumeric)'), | |
) | |
def queryset(self, request, queryset): | |
if self.value() == 'signature': | |
return queryset.order_by( | |
Coalesce(Substr('signature', V(0), NullIf(StrIndex('signature', V(' ')), V(0))), 'signature'), | |
Length('signature'), | |
'signature' | |
) | |
@register(Item) | |
class Item(ModelAdmin): | |
list_filter = [AlphanumericSignatureFilter] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
class Item(models.Model): | |
signature = models.CharField('Signatur', max_length=50) | |
def __str__(self): | |
return self.signature |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment