# Count on valid queryset raise a "OperationalError"

**URL:** <https://forum.djangoproject.com/t/count-on-valid-queryset-raise-a-operationalerror/8542>\
**Category:** Using Django\
**Created:** [June 27, 2021, 4:25am UTC](https://forum.djangoproject.com/t/count-on-valid-queryset-raise-a-operationalerror/8542 "2021-06-27T04:25:39Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![SerCor](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/sercor/32/4972_2.png) [@SerCor](https://forum.djangoproject.com/u/SerCor)\
**Post date:** [June 27, 2021, 4:25am UTC](https://forum.djangoproject.com/t/count-on-valid-queryset-raise-a-operationalerror/8542/1 "2021-06-27T04:25:39Z")

</div>

I have some model that represent a contract and has some logic to get a related amount of money **(monto\_control\_interno\_registrado)** that can be lest/equal to a expected amount **(monto\_control\_interno)**. I intent to filter the records that has the related amount **(monto\_control\_interno\_registrado)** equal to the expected amount **(monto\_control\_interno)**, and works fine but when i make a custom filter in django admin page, the pagination process execute `qs.count()` and this raise a `OperationalError: (1054, "Unknown column 'contratos.monto' in 'having clause'")`

This is the related methods in the queryset…

```auto
class ContratoQueryset(models.QuerySet):
    def with_monto_control_interno(self):
        return self.annotate(
            monto_control_interno=F('monto') * F('cambio') *
            (F('porcentaje_interno') / 100)
        )

    def with_monto_control_interno_registrado(self):
        return self.annotate(
            monto_control_interno_registrado=Coalesce(
                Sum('ingresos_control_interno__monto'), Decimal('0.00')
            )
        )

```

This is the query:

```auto
Contrato.objects.all().
    with_monto_control_interno().
    with_monto_control_interno_sin_registrar().
    filter(monto_control_interno=F('monto_control_interno_registrado'))

```

**Note.** The query get the correct result, the problem occurs when I add `.count()`, regardless of whether the query returns an empty queryset or with results, the ` OperationalError: (1054, "Unknown column 'contratos.monto' in 'having clause'")` is throwed. I am using mysql ☹
