【问题标题】:MYSQL query to Django对 Django 的 MYSQL 查询
【发布时间】:2019-01-01 12:14:45
【问题描述】:

大家好,我想在 Django 中得到这个查询,但似乎无法得到我想要的结果

SELECT DISTINCT herramienta_id,sum(cantidad)    
FROM inventario_transaccion 
WHERE 
    carrito_id = 1 and herramienta_id = 1;

此查询在 MYSQL Workbench 中返回

herramienta_id  cantidad
+--------------+---------+
|       1      |    5    |
+--------------+---------+

我要做的是获取所有带有 carrito_id = pk 的工具,并获取所有不同的值并对每个的候选值求和

【问题讨论】:

  • 不应该是GROUP BY 而不是DISTINCT
  • 谢谢,我会尝试使用 group_by 。我对编程和 mysql 有点陌生
  • 你可能想要SELECT herramienta_id, SUM(cantidad) FROM inventario_transaccion WHERE carrito_id=1 GROUP BY herramienta_id
  • 谢谢。会尝试

标签: mysql django django-views


【解决方案1】:

你没有发布你的 Django 模型,所以我只能猜测,但“在 Django”中应该是这样的。

Herramienta.objects\
    .filter(carrito_id=pk)\
    .aggregate(cantidad=Count('inventario_transaccion'))

也就是说,假设“inventario_transaccion”是另一个模型的外键上的反向 name

【讨论】:

  • 谢谢,那天晚上我设法让它工作了,我使用了以下内容:cantidades = Transaccion.objects.values('herramienta__description').annotate(Sum('cantidad')).filter(activo=True, carrito_id=pk)
猜你喜欢
  • 1970-01-01
  • 2018-05-08
  • 1970-01-01
  • 1970-01-01
  • 2016-10-05
  • 1970-01-01
  • 2016-06-04
  • 1970-01-01
  • 2011-04-09
相关资源
最近更新 更多