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. 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With