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. I tried two approaches.
Using 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
{% 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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…