Sorting a QuerySet Django using a property (not a field) of a 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 property cost. I tried two approaches.

Using order_by QuerySet API

Stops.objects.order_by('cost')

This resulted in the following template error:

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

Using the dictsort template filter

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

The following template error was received:

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

So...

How should I do it?

+5
source share
1 answer

Use QuerySet.extra()with CASE ... ENDto define a new field and sort it.

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'])

What, or discard QuerySet, returned from the rest, to the list, and then use L.sort(key=operator.attrgetter('cost'))on it.

+11

All Articles