擅长:python、mysql、java
<p>对于django>;=2.0,可以在聚合函数中使用<a href="https://docs.djangoproject.com/en/2.0/ref/models/conditional-expressions/#conditional-aggregation" rel="noreferrer">Conditional aggregation with a ^{<cd1>} argument</a>:</p>
<pre><code>from datetime import timedelta
from django.utils import timezone
from django.db.models import Count, Q # need import
Article.objects.annotate(
numviews=Count(
'readership__reader__id',
filter=Q(readership__what_time__gt=timezone.now() - timedelta(minutes=30)),
distinct=True
)
)
</code></pre>