[英]Sorting a Django QuerySet by a property (not a field) of the Model
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.我尝试了两种方法。
Stops.objects.order_by('cost')
That yielded the following template error:这产生了以下模板错误:
Caught FieldError while rendering: Cannot resolve keyword 'cost' into field.
{% 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'
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.