'Fill in the information needed for a select_related query. The current
depth is measured as the number of connections away from the root model
(for example, cur_depth=1 means we are looking at models with direct
connections to the root model).'

def fill_related_selections(self, opts=None, root_alias=None, cur_depth=1, requested=None, restricted=None, nullable=None):

    if ((not restricted) and self.query.max_depth and (cur_depth > self.query.max_depth)):
        return
    if (not opts):
        opts = self.query.get_meta()
        root_alias = self.query.get_initial_alias()
        self.query.related_select_cols = []
    only_load = self.query.get_loaded_field_names()
    if (requested is None):
        if isinstance(self.query.select_related, dict):
            requested = self.query.select_related
            restricted = True
        else:
            restricted = False
    for (f, model) in opts.get_fields_with_model():
        field_model = (model or f.model)
        if (not select_related_descend(f, restricted, requested, only_load.get(field_model))):
            continue
        promote = (nullable or f.null)
        (_, _, _, joins, _) = self.query.setup_joins([f.name], opts, root_alias, outer_if_first=promote)
        alias = joins[(-1)]
        (columns, _) = self.get_default_columns(start_alias=alias, opts=f.rel.to._meta, as_pairs=True)
        self.query.related_select_cols.extend((SelectInfo((col[0], col[1].column), col[1]) for col in columns))
        if restricted:
            next = requested.get(f.name, {})
        else:
            next = False
        new_nullable = (f.null or promote)
        self.fill_related_selections(f.rel.to._meta, alias, (cur_depth + 1), next, restricted, new_nullable)
    if restricted:
        related_fields = [(o.field, o.model) for o in opts.get_all_related_objects() if o.field.unique]
        for (f, model) in related_fields:
            if (not select_related_descend(f, restricted, requested, only_load.get(model), reverse=True)):
                continue
            (_, _, _, joins, _) = self.query.setup_joins([f.related_query_name()], opts, root_alias, outer_if_first=True)
            alias = joins[(-1)]
            from_parent = (opts.model if issubclass(model, opts.model) else None)
            (columns, _) = self.get_default_columns(start_alias=alias, opts=model._meta, as_pairs=True, from_parent=from_parent)
            self.query.related_select_cols.extend((SelectInfo((col[0], col[1].column), col[1]) for col in columns))
            next = requested.get(f.related_query_name(), {})
            new_nullable = True
            self.fill_related_selections(model._meta, alias, (cur_depth + 1), next, restricted, new_nullable)
