Django annotate allows us to add a pseudo field to our queryset.
read this blog: https://medium.com/@singhgautam7/django-annotations-steroids-to-your-querysets-766231f0823a
xxxxxxxxxx
Model.objects.annotate(<field_name>=<value>)
field_name: can be anything that you want.
value: whatever the value is.
xxxxxxxxxx
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
)
)
from django.db.models import Count, Case, When, IntegerField
Article.objects.annotate(
numviews=Count(Case(
When(readership__what_time__lt=treshold, then=1),
output_field=IntegerField(),
))
)