[Answered ]-Django annotate with frequency

1👍

Found a workaround:

users = User.objects.filter(
    Q(...)
).annotate(
    login_count=Count('userlog', filter=Q(userlog__login=True)),
    login_duration_over=Now() - F('created_datetime'),
    login_frequency=Cast(
        ExpressionWrapper(
            Cast(F('login_duration_over'), output_field=models.BigIntegerField()) / F('login_count'),
            output_field=models.BigIntegerField()
        ),
        output_field=models.DurationField()
    )
)

this forces the DIVIDE operation to be performed db-side on bigints and once that is done, cast it back to a timedelta.

MySQL stopped screaming and the results are correct.

Even though that work, this feels ugly. Could there not be a better way?

👤Hal

Leave a comment