Hello all,
models.py
:
class User(models.Model):
email = models.EmailField(...)
created_datetime = models.DatetimeField(...)
class UserLog(models.Model):
created_datetime = models.DatetimeField(...)
user = models.ForeignKey('user.User' ...)
login = models.BooleanField('Log in' ..)
And the following query:
users = User.objects.filter(
Q(...)
).annotate(
login_count=SubqueryCount(
UserLog.objects.filter(
user__pk=OuterRef('pk'),
login=True,
),
output_field=models.IntegerField(),
),
login_frequency=ExpressionWrapper(
(Now() - F('created_datetime')) / F('login_count'),
output_field=models.DurationField()
),
)
SubqueryCount
being this:
class SubqueryCount(Subquery):
template = "(SELECT COUNT(*) FROM (%(subquery)s) _count)"
The error is:
MySQLdb._exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '/ (SELECT COUNT(*)
The problematic generated SQL seems to be this:
(
INTERVAL TIMESTAMPDIFF(
MICROSECOND,
`user_user`.`created_datetime`,
CURRENT_TIMESTAMP
) MICROSECOND / (
SELECT
COUNT(*)
FROM
(
SELECT
U0.`id`
FROM
`user_userlog` U0
WHERE
(
U0.`user_id` = `user_user`.`id`
AND U0.`login`
)
) _count
)
) AS `login_frequency`,
Django 3.2.12, Python 3.9.3, Mysql 8.0.28