1

query for model instances that are indirectly related

I've got 3 models. I'd like to write a query in django to find all reviews that are related to Carts that are related to jobs that are complete. Unfortunately, I can't figure out how to do this.

class Review:
   cart = models.ForeignKey(Cart, on_delete=models.CASCADE, default=None)   

class Job:
   cart = models.ForeignKey(Cart, on_delete=models.CASCADE, default=None)   
   complete = models.BooleanField(default=False)

class Cart:
   name = models.CharField(max_length=500, null=True, blank=True)
   amount = models.IntegerField()

Any help would be appreciated!

Submitted July 25th 2021 by Admin

Answers
0

You can .filter(…) [Django-doc] with:

Review.objects.filter(cart__job__complete=True)

One can use double underscores (__) to look "through" relations.

This will thus retrieve all Reviews for which a related Cart exists for which a related Job exists that has complete=True.

Admin | 1 month ago



Relevant Questions