To make my question more understandable, here’s an example.
There are two models:
class A(models.Model):
name = models.CharField(max_length = 10)
class B(models.Model):
a = models.ForeignKey(A)
name = models.CharField(max_length = 10)
So in this example, A and B are of one-to-many relationship. Now let’s say I’d like to make the following query: find an A that has at least one B as child. In sql, clearly I should use exists clause. Is it possible to achieve exactly the same with orm?
I’ve done some research on that but can’t find a perfect match to the sql query. The closest solution is like:
A.objects.filter(b__pk__gt = 0).distinct()
But it’s still far from the exists clause in sql and might not be as efficient as exists.
The following will select all
As that have one or more associatedBs:Switching it to
b__isnull=Truewill select onlyAs that have noBs associated with them.