예제 #1
0
 def with_advice_status(self):
     return self.annotate(advice_count=Count("advice")).annotate(
         has_advice=expressions.Case(
             expressions.When(advice_count=0, then=False),
             default=True,
             output_field=BooleanField(),
         ))
예제 #2
0
def IsNotNone(*fields, default=None):
    """Selects whichever field is not None, in the specified order.

    Arguments:
        fields:
            The fields to attempt to get a value from,
            in order.

        default:
            The value to return in case all values are None.

    Returns:
        A Case-When expression that tries each field and
        returns the specified default value when all of
        them are None.
    """

    when_clauses = [
        expressions.When(~expressions.Q(**{field: None}),
                         then=expressions.F(field))
        for field in reversed(fields)
    ]

    return expressions.Case(
        *when_clauses,
        default=expressions.Value(default),
        output_field=CharField(),
    )
예제 #3
0
 def get_queryset(self) -> models.QuerySet:
     qs = self.queryset.annotate(has_user=expressions.Case(
         expressions.When(
             user__isnull=False,
             then=expressions.Value(True),
         ),
         default=expressions.Value(False),
         #
         # Tell Django the expected type of the field, see `output_field` in
         # https://docs.djangoproject.com/en/2.1/ref/models/expressions/
         #
         output_field=models.BooleanField()))
     logger.info(qs.query)
     return qs