Let's imagine I have 2 models:
Class Tree(models.Model):
title = models.CharField(max_length=255)
Class Apple(models.Model):
tree = models.ForeignKey(Tree, related_name="apples")
How do I select all the Trees that have Apples.
I mean I want to select all the Trees that exist in Apple Model from an instance of Tree
.
I think I want to execute this query:
SELECT DISTINCT tree.id, tree.title
FROM apple JOIN tree ON apple.tree = tree.id
Untill now i have written 2 queries and they are working but I think they are not the best practices to do it:
Tree.objects.filter(
apples__tree__in=Apple.objects.all().values_list("tree")
).distinct()
Tree.objects.filter(apples__tree__isnull=False).distinct()