Django ORM - LEFT JOIN Table2 ON Table2.Column = 123

Django ORM - LEFT JOIN Table2 ON Table2.Column = 123

我想要实现的目标:

http://sqlfiddle.com/#!5/dccc4/5

数据库方案:

CREATE TABLE Table1 
(
 idTable1 integer primary key
);

CREATE TABLE Table2
(
  idTable1 integer,
  user_id integer,
  num integer
);

INSERT INTO Table1 (idTable1) VALUES (1);
INSERT INTO Table1 (idTable1) VALUES (2);
INSERT INTO Table2 (idTable1, user_id, num) VALUES (1, 11, 111);
INSERT INTO Table2 (idTable1, user_id, num) VALUES (1, 22, 222);

原始 SQL 查询:

SELECT    T1.idTable1,
          IFNULL(T2.num, 0) num
FROM      Table1 T1
LEFT JOIN Table2 T2 
ON        T1.idTable1 = T2.idTable1 
AND       T2.user_id  = 11
WHERE     T1.idTable1 = 1

结果查询集:

| idTable1 | num |
|----------|-----|
|        1 | 111 |

是否可以使用 Django ORM 进行编码?

更新

型号为:

class Table1(models.Model):
    # ...

class Table2(models.Model):
    user = models.ForeignKey(User)
    table1 = models.ForeignKey(Table1)

    num = models.IntegerField(null=True)

像这样:

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')

LEFT JOIN,但我不知道Django是否可以在... LEFT JOIN ... ON ... AND ... WHERE这样的查询中构造AND部分。在这种情况下,最终结果是相同的(我希望)。