【发布时间】: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.
我的问题是否与语句的“当用作可迭代时”部分有关?如何按附加值对这种查询集进行排序?
提前致谢!
【问题讨论】: