[Solved]-Django: conditional expression

20👍

I think you want to be using a Case here.

def get_queryset(self):

    agreements = _agreement_model.Agreement.objects.filter(
        organization=self.organization
    ).annotate(
        signed=Case(When(signed_agreement__member=F('member')),
                    then=Value(True),
                    default=Value(False),
                    output_field=BooleanField()
    ).order_by(
        'name'
    )

    return agreements

UPDATE

Per comments it appears that in later versions of Django that the then must be passed in the When

def get_queryset(self):

    agreements = _agreement_model.Agreement.objects.filter(
        organization=self.organization
    ).annotate(
        signed=Case(When(signed_agreement__member=F('member'), 
                         then=Value(True)
                    ),
                    default=Value(False),
                    output_field=BooleanField()
    ).order_by(
        'name'
    )

    return agreements

3👍

Accepted answer didn’t work for me with Django 1.11.6. I had to put then inside When to make it work.

from django.db.models import Case, When, F, BooleanField


def get_queryset(self):
    agreements = _agreement_model.Agreement.objects.filter(
        organization=self.organization
    ).annotate(
        signed=Case(
            When(
                signed_agreement__member=F('member'),
                then=True
            ),
            default=False,
            output_field=BooleanField()
        )
    ).order_by(
        'name'
    )

Leave a comment