如何在没有注释的情况下向查询集添加having子句?

时间:2022-06-12 05:32:43

Hello I have this queryset:

您好我有这个查询集:

visitas = 
Visitas_Paciente.objects.filter(fecha__range= g.get('fecha_inicio'), 
g.get('fecha_fin'))).values('paciente_id').annotate(numeros=
Sum('numero')).filter(qNumeroVisitas).order_by('numeros')

with this sql equivalent:

用这个SQL等价物:

SELECT `ES_visitas_paciente`.`paciente_id`, 
SUM(`ES_visitas_paciente`.`numero`) AS `numeros` FROM 
`ES_visitas_paciente` WHERE `ES_visitas_paciente`.`fecha` 
BETWEEN 2012-01-01 AND 2013-01-01 GROUP BY 
`ES_visitas_paciente`.`paciente_id` HAVING 
SUM(`ES_visitas_paciente`.`numero`) >= 4 ORDER BY `numeros` ASC

the problem is that I dont want the 'numeros' column, I just want the id, something like this query:

问题是我不想要'numeros'列,我只想要id,就像这个查询:

SELECT
`ES_visitas_paciente`.`paciente_id` 
FROM `ES_visitas_paciente`
WHERE `ES_visitas_paciente`.`fecha` BETWEEN '2012-01-01' AND '2013-01-01'
GROUP BY `ES_visitas_paciente`.`paciente_id`
HAVING SUM(`ES_visitas_paciente`.`numero`) > 4

please help me :(

请帮我 :(

1 个解决方案

#1


0  

Basically we need to limit the selection. We can do this by adding additional .values(paciente_id). Here is a documentation After this we will have

基本上我们需要限制选择。我们可以通过添加额外的.values(paciente_id)来实现。这是一个文档在此之后我们将有

visitas = Visitas_Paciente.objects.filter(
    fecha__range=(g.get('fecha_inicio'),g.get('fecha_fin'))
).values(
    'paciente_id'
).annotate(
    numeros=Sum('numero')
).filte‌​r(
    numeros > 4
).orde‌​r_by(
    'numeros'
).values(
    'paciente_id'
)

Here we

  1. filter by the fecha(date),
  2. 过滤(日期),

  3. create the group by paciente_id,
  4. 通过paciente_id创建组,

  5. make the Sum by groups (docs),
  6. 按组(docs)制作Sum,

  7. filter it by numeros>4,
  8. 过滤它由numeros> 4,

  9. order it.
  10. Than we get only 'paciente_id'.
  11. 比我们只得到'paciente_id'。

Be careful - there are 2 values('paciente_id') statements.

小心 - 有2个值('paciente_id')语句。

Hope it helps!

希望能帮助到你!

#1


0  

Basically we need to limit the selection. We can do this by adding additional .values(paciente_id). Here is a documentation After this we will have

基本上我们需要限制选择。我们可以通过添加额外的.values(paciente_id)来实现。这是一个文档在此之后我们将有

visitas = Visitas_Paciente.objects.filter(
    fecha__range=(g.get('fecha_inicio'),g.get('fecha_fin'))
).values(
    'paciente_id'
).annotate(
    numeros=Sum('numero')
).filte‌​r(
    numeros > 4
).orde‌​r_by(
    'numeros'
).values(
    'paciente_id'
)

Here we

  1. filter by the fecha(date),
  2. 过滤(日期),

  3. create the group by paciente_id,
  4. 通过paciente_id创建组,

  5. make the Sum by groups (docs),
  6. 按组(docs)制作Sum,

  7. filter it by numeros>4,
  8. 过滤它由numeros> 4,

  9. order it.
  10. Than we get only 'paciente_id'.
  11. 比我们只得到'paciente_id'。

Be careful - there are 2 values('paciente_id') statements.

小心 - 有2个值('paciente_id')语句。

Hope it helps!

希望能帮助到你!