简体   繁体   中英

Sort a Django queryset based on the values in the choice field

I have a model,

class Example(models.Model):
MY_CHOICES = (
    ("yes", _("Yes")),
    ("no", _("NO")),
    ("not_sure", _("Not sure")),
)
name = models.CharField(max_length=200, verbose_name=_('Name'))
status = models.CharField(max_length=100,choices=MY_CHOICES,default='yes')

I need to get the query set sorted in the get_queryset method, ie,

def get_queryset(self, request):
    qs = self.model._default_manager.get_queryset()
    order = ['yes', 'no', 'not_sure']
    qs = #CODE TO ORDER THE S HERE BASED ON order.
    return qs

*The return value i need is a QuerySet not a sorted list. *The qs need to be sorted based on the the status value according to the order 'yes', 'no', 'not_sure'.

Please Note: I need thr QS based on the object attribute value(ie, status value). In the order objects of status='yes' first followed by 'no' and 'not_sure'

Given this previous SO Q/A

and keeping your code, I'd say

def get_queryset(self, request):
    qs = self.model._default_manager.get_queryset()
    order = ['yes', 'no', 'not_sure']
    return sorted(qs, key=lambda x: order.index(x.status))

However, I'd rather have the DB do it instead. Have a look at this QA for a nice trick:

ORDER BY idx(array['yes', 'no', 'not_sure'], status)

Add the SQL fragment above to the query generated by django's ORM (or create one ex-novo) and perform a raw query with it:

def get_queryset(self, request):
    qs = self.model._default_manager.get_queryset()
    newquery = qs.query+' ORDER BY idx(array'+order.__str__()+', status)'
    return self.model._default_manager.raw(newquery)

It should work, provided there is no order by clause already in the sql. I haven't tested it yet.

Update for newer Django versions (tested in v3.0.10), without custom SQL syntax, using conditional expressions :

from django.contrib import admin
from django.db.models import Case, When, Value

class ExampleAdmin(admin.ModelAdmin):    
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.order_by( Case( 
                       When ( status="yes", then=Value(0) ),
                       When ( status="no", then=Value(1)  ),
                       default = Value(2)
                          )
                    )

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