Django: conditional expression

Viewed 8268

I have the following models:

class Agreement(models.Model):
    ...
    organization = models.ForeignKey("Organization")

class Signed_Agreement(models.Model):
    agreement = models.ForeignKey("Agreement")
    member = models.ForeignKey("Member")

What I'm trying to do is get a list of all the agreements for a particular organization (self.organization) and annotate each agreement with information about whether or not it has been signed by a particular member (self.member).

If the Agreement has been signed, then there exists an instance of Signed_Agreement for the particular agreement and member.

How do I write a query for this?

Here's my effort so far:

from django.db.models import When, F, Q, Value

def get_queryset(self):

    agreements = _agreement_model.Agreement.objects.filter(
        organization=self.organization
    ).annotate(
        signed=When(Q(signed_agreement__member=self.member), then=Value(True))
    ).order_by(
        'name'
    )

    return agreements

This is not producing the correct results.

Any help would be appreciated. Thanks in advance.

2 Answers

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