1

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?

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
th3plus
  • 161
  • 2
  • 11

1 Answers1

1

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()
Sören Rifé
  • 518
  • 1
  • 4
  • sure but i want to annotate the boolean value to test 1 objects because i used fetch_related method to fetch the test2 related objects – th3plus Sep 14 '22 at 18:01