[Fixed]-Django ORM – LEFT JOIN Table2 ON Table2.Column = 123

1👍

Something like this:

from django.db.models import Q, Value as V
from django.db.models.functions import Coalesce

objects = Table1.objects.filter(
              Q(table2__isnull=True) | Q(table2__user=11),
              id=1
          ).annotate(
              num=Coalesce('table2__num', V(0))
          ).values('id', 'num')

It is LEFT JOIN, but I don’t know if Django can construct AND part in queries like ... LEFT JOIN ... ON ... AND ... WHERE. In this case, end result is the same (I hope).

👤f43d65

Leave a comment