我在Django数据库聚合bug中提到了,Django在处理多表聚合会出现bug,其原因是在做数据表的连接操作时接错了一些表。现在么,这个问题我是靠着自定义sql来处理的。不过昨天在闲逛的时候发现了另一种方法,利用django.db.models.sql.query.BaseQuery的join函数。具体的例子可以参考这篇来源。
这是join函数的文档:
join(self, connection, always_create=False, exclusions=(), promote=False,
outer_if_first=False, nullable=False, reuse=None)
Returns an alias for the join in 'connection', either reusing an
existing alias for that join or creating a new one. 'connection' is a
tuple (lhs, table, lhs_col, col) where 'lhs' is either an existing
table alias or a table name. The join correspods to the SQL equivalent
of::
lhs.lhs_col = table.col
If 'always_create' is True and 'reuse' is None, a new alias is always
created, regardless of whether one already exists or not. If
'always_create' is True and 'reuse' is a set, an alias in 'reuse' that
matches the connection will be returned, if possible. If
'always_create' is False, the first existing alias that matches the
'connection' is returned, if any. Otherwise a new join is created.
If 'exclusions' is specified, it is something satisfying the container
protocol ("foo in exclusions" must work) and specifies a list of
aliases that should not be returned, even if they satisfy the join.
If 'promote' is True, the join type for the alias will be LOUTER (if
the alias previously existed, the join type will be promoted from INNER
to LOUTER, if necessary).
If 'outer_if_first' is True and a new join is created, it will have the
LOUTER join type. This is used when joining certain types of querysets
and Q-objects together.
If 'nullable' is True, the join can potentially involve NULL values and
is a candidate for promotion (to "left outer") when combining querysets.
虽然我还没有尝试,不过如果以后发现数据表连接出现错误时,这个方法会优先考虑一下。不过join有个问题是没有右联和全联接的支持,对于这样的情况目前还是得依靠自己的双手了……

