'A helper method for get_ordering and get_distinct. This method will
call query.setup_joins, handle refcounts and then promote the joins.
Note that get_ordering and get_distinct must produce same target
columns on same input, as the prefixes of get_ordering and get_distinct
must match. Executing SQL where this is not true is an error.'

def _setup_joins(self, pieces, opts, alias):

    if (not alias):
        alias = self.query.get_initial_alias()
    (field, target, opts, joins, _, _) = self.query.setup_joins(pieces, opts, alias, False)
    joins_to_promote = [j for j in joins if (self.query.alias_refcount[j] < 2)]
    alias = joins[(-1)]
    col = target.column
    if (not field.rel):
        self.query.ref_alias(alias)
    self.query.promote_joins(joins_to_promote)
    return (field, col, alias, joins, opts)
