使用query.join连接django中的表

时间:2013-12-10 20:37:16

标签: sql django join

在django< 1.3在BaseQuery模型中有一个带有此签名的方法.join:

def 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
     """

所以要使连接全部需要,就像在这个例子中一样:http://www.caktusgroup.com/blog/2009/09/28/custom-joins-with-djangos-queryjoin/

# setup intial FROM clause
# OR contacts.query.get_initial_alias()
contacts.query.join((None, 'crm_contact', None, None))
# join to crm_contact_phones
connection = (
    'crm_contact',
    'crm_contact_phones',
    'id',
    'contact_id',
)
contacts.query.join(connection, promote=True)

现在在django 1.6中,签名发生了变化,我再也不能这样了:

def join(self, connection, reuse=None, outer_if_first=False,
         nullable=False, join_field=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, join_cols) where 'lhs' is either an existing
    table alias or a table name. 'join_cols' is a tuple of tuples containing
    columns to join on ((l_id1, r_id1), (l_id2, r_id2)). The join corresponds
    to the SQL equivalent of::

        lhs.l_id1 = table.r_id1 AND lhs.l_id2 = table.r_id2
    """

每当我通过join_cols传递连接时,它都会失败,因为它要求join_field,我真的不知道该传递给它。

0 个答案:

没有答案