通过Model的属性(不是字段)对Django QuerySet进行排序

Bel*_*dez 9 python django-templates django-models

一些代码和我的目标

我的(简化)模型:

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

    STOP_TYPES = (
        (EXPRESS_STOP, 'Express stop'),
        (LOCAL_STOP, 'Local stop'),
    )

    name = models.CharField(max_length=32)
    type = models.PositiveSmallIntegerField(choices=STOP_TYPES)
    price = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)

    def _get_cost(self):
        if self.price == 0:
            return 0
        elif self.type == self.EXPRESS_STOP:
            return self.price / 2
        elif self.type == self.LOCAL_STOP:
            return self.price * 2
        else:
            return self.price    
    cost = property(_get_cost)
Run Code Online (Sandbox Code Playgroud)

我的目标:我想按照cost物业排序.我尝试了两种方法.

使用order_by QuerySet API

Stops.objects.order_by('cost')
Run Code Online (Sandbox Code Playgroud)

这产生了以下模板错误:

Caught FieldError while rendering: Cannot resolve keyword 'cost' into field.
Run Code Online (Sandbox Code Playgroud)

使用dictsort模板过滤器

{% with deal_items|dictsort:"cost_estimate" as items_sorted_by_price %}
Run Code Online (Sandbox Code Playgroud)

收到以下模板错误:

Caught VariableDoesNotExist while rendering: Failed lookup for key [cost] in u'Union Square'
Run Code Online (Sandbox Code Playgroud)

所以...

我应该怎么做呢?

Ign*_*ams 15

使用QuerySet.extra()连同CASE ... END定义一个新的领域,和排序上.

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'])
Run Code Online (Sandbox Code Playgroud)

那,或者将QuerySet其余的返回到一个列表,然后使用L.sort(key=operator.attrgetter('cost'))它.

  • `key = lambda x:x.pricing.cost` (3认同)