【问题标题】:Django: ordering a queryset by dictionary added valuesDjango:按字典添加值排序查询集
【发布时间】:2019-08-14 10:34:39
【问题描述】:

我正在尝试对添加了一些计算值的字典查询集进行排序。

过程:

class Inventario(models.Model):
    codigo_kinemed = models.CharField(max_length=100)
    existencias = models.IntegerField(help_text="Existencias ", blank=True, null=True)
    valor_coste = models.IntegerField(help_text="Existencias ", blank=True, null=True)
    valor_venta = models.IntegerField(help_text="Existencias ", blank=True, null=True)
    fecha = models.DateField(help_text="Fecha de toma de datos", blank=True, null=True)

    def __str__(self):
        return str(self.codigo_kinemed)

我从中得到一个查询集。

inventario_diferencia = Inventario.objects.filter(fecha=ultima_fecha_cargada.fecha).values()

返回一个查询集的字典。然后我遍历该查询集并计算一些新字段。

for este in inventario_diferencia:
    este['stock_valor_venta'] = este['existencias'] * este['valor_venta']

我可以在模板中毫无问题地打印该计算字段。

{{ inventario_diferencia.stock_valor_venta }}

排序

我想按我添加的新 stock_valor_ventavalue 对该查询集进行排序。

当我尝试通常的查询集时

inventario_diferencia.order_by('stock_valor_venta')

我明白了:

无法将关键字“diferencia_mes”解析为字段。选择有:codigo_kinemed、existencias、fecha、id、valor_coste、valor_venta

这些是模型的原始值,因此无法按新值排序。当我尝试像字典一样对其进行排序时

inventario_diferencia = sorted(inventario_diferencia, key=lambda t: t.diferencia_mes)

我明白了

'dict' 对象没有属性'diferencia_mes'

文档

在 Django 文档 https://docs.djangoproject.com/en/2.1/ref/models/querysets/#values 中声明如下:

values(*fields, **expressions) Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.

我的问题是否与语句的“当用作可迭代时”部分有关?如何按附加值对这种查询集进行排序?

提前致谢!

【问题讨论】:

    标签: django django-queryset


    【解决方案1】:

    您应该考虑使用annotate。您可以创建一个等于两个字段乘积的字段,然后在 SQL 中按该字段排序。

    from django.db.models import F
    inventario_diferencia = Inventario.objects.filter(
        fecha=ultima_fecha_cargada.fecha
    ).annotate(
        stock_valor_venta=F('existencias') * F('valor_venta')
    ).order_by('-stock_valor_venta')
    
    print(inventorio_deiferencia.first().stock_valor_venta)
    

    【讨论】:

    • 如果我有一个与来自其他查询的计算相关的注释怎么办?比如:venta_historica=ventas.filter(prod_codigo=F('codigo_kinemed')).aggregate(Sum("uds")).get("uds__sum")
    • 我不明白你在问什么。
    • 我会开始另一个问题
    猜你喜欢
    • 2020-08-16
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 2012-07-30
    • 2016-05-23
    • 2019-01-13
    • 2020-07-16
    • 1970-01-01
    相关资源
    最近更新 更多