th3plus
th3plus

Reputation: 323

annotating by one-to-many relationship in Django

Let's say I have these two models:

class Test1:
   ...........
class Test2:
    test1 = models.ForeignKey(Test1, related_name = 'tests')
    isCompleted = models.BooleanField()

and I want to make this query:

queryset = Test1.objects.annotate(is_completed = ExpressionWrapper(Q(tests__isCompleted = True ),output_field = BooleanField()))

of course this is giving me a None when I do this:

queryset[0].tests.first().is_completed

What I am trying to do is I want to check if only one of the related tests(the related objects to Test1) has a field isCompleted with the value True. So my question is what's is the right way to do this?

Upvotes: 1

Views: 217

Answers (1)

Sören Rifé
Sören Rifé

Reputation: 538

If you have an instance of Test1 (saved as test1, for example) and you just want to know if that instance has any related Test2 with isCompleted you could do:

Test2.objects.filter(isCompleted=True, test1=test1.id).exists()

This would return a boolean of whether or not exists a Test2 with isCompleted = True related to your Test1.

If what you want is to get all Test1 that has at least one related Test2 with isCompleted = True, you could do:

Test1.objects.filter(tests__isCompleted=True).distinct()

Upvotes: 1

Related Questions