Django: can i achieve the same as sql?

To make my question clearer, 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 have a one-to-many relationship. Now, let's say that I would like to make the following query: find A that has at least one B as a child. In sql, obviously I have to use an existence condition. Is it possible to achieve the same result with orm?

I have done some research on this but cannot find a perfect match for the sql query. The closest solution:

A.objects.filter(b__pk__gt = 0).distinct()

      

But it is still far from the exists clause in sql and may not be as efficient as it already exists.

+3


source to share


2 answers


Next, let's select all A

that have one or more related B

s:

A.objects.filter(b__isnull=False)

      



Switching to b__isnull=True

will only select A

those that do not have B

one associated with them.

+1


source


In fact (if I haven't misunderstood what you are trying to do) with plain sql, a simple left join would be a path, not an EXISTING clause.

Your query works very well without .distinct ()



I recommend that you take a look at the queries generated by the django orm so you can see what is going on and actually run ANALYZE / EXPLAIN instead of guessing the characteristics.

You can see the unhandled request from the request attribute of the queryset, or better yet, install the django debug toolbar and see all the requests for a given request.

+1


source







All Articles