Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

python - 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. 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...