How to annotate Count with a condition in a Django queryset

前端 未结 2 1919
囚心锁ツ
囚心锁ツ 2020-11-28 21:51

Using Django ORM, can one do something like queryset.objects.annotate(Count(\'queryset_objects\', gte=VALUE)). Catch my drift?


Here\'s a quick ex

2条回答
  •  悲&欢浪女
    2020-11-28 22:15

    For django >= 2.0 you can use Conditional aggregation with a filter argument in the aggregate functions:

    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
        )
    )
    

提交回复
热议问题