Annotation to count and return zero when there is no relation

前端 未结 2 1235
小蘑菇
小蘑菇 2021-01-14 15:12

Given the following relation:

class LicenseRequest:
    license_type = models.ForeignKey(LicenseType)
    created_at = models.DateField(default=now, editable         


        
相关标签:
2条回答
  • 2021-01-14 15:44

    In djang-2.0 and higher, the Count object has a filter parameter, so we can specify the conditions for this:

    qs = LicenseType.objects.annotate(
        rel_count=Count(
            'licenserequest',
            filter=Q(licenserequest__created_at__range=(start_date, end_date))
        )
    )

    For djang-1.11 and below, we can use the Sum(..) of a Case(..) expression:

    qs = LicenseType.objects.annotate(
        rel_count=Sum(Case(
            When(
                licenserequest__created_at__range=(start_date, end_date),
                then=1
            ),
            default=0,
            output_field=IntegerField()
        ))
    )
    
    0 讨论(0)
  • 2021-01-14 15:50
    qs = LicenseType.objects.annotate(count=Count('licenserequest__id')
    condition = Q(licenserequest__created_at__range=(start_date, end_date)) & Q(licenserequest__isnull=True)
    qs = qs.annotate(Case(When(condition, then=F('count')), default=0, output_field=IntegerField())
    

    This should work for the model description that you have provided. To do the later filter, you cannot use a direct .filter() but rather use a Case/When .annotate() clause

    0 讨论(0)
提交回复
热议问题