1

I have been thru endless posts on Django and the LEFT JOIN problem and but have not found anyone that has a solution in the 2.2 version of Django. Whilst in years past it seems there were ways to get around this problem, the Django team seem to have shut down every mechanism people have employed to achieve the most simple but necessary query - the LEFT JOIN. Here is a simle example of what I am trying to do (it is a simple example to reflect a real world scenario so please do not offer ways to redesign the models... all I want is the age old LEFT JOIN in SQL .... that simple):

from django.db import models
from uuid import uuid4
class People(models.Model):
    id = models.UUIDField(primary_key=True, editable=False, default=uuid4)
    name = models.CharField(max_length=255)


class Book(models.Model):
    id = models.UUIDField(primary_key=True, editable=False, default=uuid4)
    name = models.CharField(max_length=255)
    author = models.ForeignKey(People)
    publisher = models.ForeignKey(People, on_delete=models.PROTECT, null=True)

How would I achive an output showing all books and the publisher if there is a publisher (otherwise just blank)

Books.objects.filter(Q(publisher__isnull=True | Q(publisher__isnull=False)

... produces an INNER JOIN which will obviously only show books that have a publisher assigned. The query I am looking for would be of the form: select * from book LEFT JOIN people ON book.publisher_id=people.id

... or do I have to resort to raw SQL for this most simple of requirements?

1 Answer 1

1

You can perform a .select_related(..) [Django-doc] here:

Book.objects.select_related('publisher')

This will fetch both the Book data and the related Publisher if it exists. So some_book.publisher where some_book originates from this queryset, will not result in an extra query to fetch the publisher. The query this will look like:

SELECT book.id, book.name, book.author_id, book.publisher_id,
       people.id, people.name
FROM book
LEFT OUTER JOIN people ON book.publisher_id = people.id
5
  • I have seen that select_related performs inner join, but here it is left outer join. It is because of null=True in ForeignKey or am I missing something? Oct 3, 2019 at 12:35
  • 1
    @NalinDobhal: well it usually performs a LEFT OUTER JOIN. But for non-nullable fields, it can be optimized to an INNER JOIN :). I think it is thus strictly speaking the other way around. But it boils down to the same :) You can check it with print(Book.objects.select_related('publisher').query), which indeed yields a LEFT OUTER JOIN. Oct 3, 2019 at 12:36
  • Well I should have actually run my simplified model and tested before posting it ... in my "real life" model that has a foreign key to another model exactly as depicted in the relations above, that same select_related() method still produces an INNER JOIN ... will try to figure out what is causing Django to decide NOT to use a LEFT JOIN for my case Oct 4, 2019 at 12:57
  • @ChristopherBroderick: usually that is because the Django ORM found a something why it is not necessary to use a LEFT JOIN. It is thus an "optimization" to transform LEFT JOINs to INNER JOINs. Either that is a valid reason, or a bug. Oct 4, 2019 at 12:59
  • My own stupidity ... the ForeignKey field was required not optional and therefore a LEFT JOIN is inefficient and unnecessary Oct 4, 2019 at 13:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.