python - 通过模型的属性(而不是字段)对 Django QuerySet 进行排序

标签 python django-models django-templates

一些代码和我的目标

我的(简化的)模型:

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)

我的目标:我想按 cost 属性排序。我尝试了两种方法。

使用 order_by 查询集 API

Stops.objects.order_by('cost')

这产生了以下模板错误:

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

使用dictsort模板过滤器

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

收到以下模板错误:

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

所以...

我应该怎么做?

最佳答案

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

那个,或者将从 rest 返回的 QuerySet 转换为列表,然后在其上使用 L.sort(key=operator.attrgetter('cost')) .

关于python - 通过模型的属性(而不是字段)对 Django QuerySet 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4175749/

相关文章:

python - 在 Python 中通过 global 关键字从外部作用域访问变量

django - 皮查姆 : makemigrations and migrate ignore my changes

django-models - 如何在管理页面中显示模型的所有字段?

python - Django过滤器查询过滤器参数是否存在

python - GraphQL/Graphene 用于 Django 模板中的后端调用

python - 正则表达式捕获所有导入语句

Python修饰函数保留部分签名

python - 使用文件和路径的最佳实践是什么?

javascript - include 标签内的 url 标签中的 NoReverseMatch

Django 模板标签如果未按预期进行比较