简体   繁体   English

按模型的属性(而不是字段)对 Django QuerySet 进行排序

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

Some code and my goal一些代码和我的目标

My (simplified) model:我的(简化)模型:

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)

My Goal : I want to sort by the cost property.我的目标:我想按cost属性排序。 I tried two approaches.我尝试了两种方法。

Using order_by QuerySet API使用 order_by QuerySet API

Stops.objects.order_by('cost')

That yielded the following template error:这产生了以下模板错误:

Caught FieldError while rendering: Cannot resolve keyword 'cost' into field.

Using dictsort template filter使用 dictsort 模板过滤器

{% with deal_items|dictsort:"cost_estimate" as items_sorted_by_price %}

Received the following template error:收到以下模板错误:

Caught VariableDoesNotExist while rendering: Failed lookup for key [cost] in u'Union Square'

So...所以...

How should I go about doing this?我该怎么做呢?

Use QuerySet.extra() along with CASE ... END to define a new field, and sort on that.使用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'])

That, or cast the QuerySet returned from the rest to a list, then use L.sort(key=operator.attrgetter('cost')) on it.那,或者将从其余部分返回的QuerySet转换为列表,然后在其上使用L.sort(key=operator.attrgetter('cost'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM