Sorting a Django QuerySet by a property (not a field) of the Model

前端 未结 1 1437
[愿得一人]
[愿得一人] 2020-11-30 05:16

Some code and my goal

My (simplified) model:

class Stop(models.Model):
    EXPRESS_STOP = 0
    LOCAL_STOP   = 1

    STOP_TYPES = (
        (EXPRE         


        
相关标签:
1条回答
  • 2020-11-30 05:50

    Use QuerySet.extra() along with CASE ... END to define a new field, and sort on that.

    Stops.objects.extra(select={'cost': 'CASE WHEN price=0 THEN 0 '
      'WHEN type=:EXPRESS_STOP THEN price/2 WHEN type=:LOCAL_STOP THEN price*2'},
      order_by=['cost'])
    

    That, or cast the QuerySet returned from the rest to a list, then use L.sort(key=operator.attrgetter('cost')) on it.

    0 讨论(0)
提交回复
热议问题