'The \'target\' parameter is the final field being joined to, \'joins\'
is the full list of join aliases. The \'path\' contain the PathInfos
used to create the joins.
Returns the final target field and table alias and the new active
joins.
We will always trim any direct join if we have the target column
available already in the previous table. Reverse joins can\'t be
trimmed as we don\'t know if there is anything on the other side of
the join.'

def trim_joins(self, targets, joins, path):

    for (pos, info) in enumerate(reversed(path)):
        if ((len(joins) == 1) or (not info.direct)):
            break
        join_targets = set((t.column for t in info.join_field.foreign_related_fields))
        cur_targets = set((t.column for t in targets))
        if (not cur_targets.issubset(join_targets)):
            break
        targets = tuple((r[0] for r in info.join_field.related_fields if (r[1].column in cur_targets)))
        self.unref_alias(joins.pop())
    return (targets, joins[(-1)], joins)
