'When doing an exclude against any kind of N-to-many relation, we need
to use a subquery. This method constructs the nested query, given the
original exclude filter (filter_expr) and the portion up to the first
N-to-many relation field.
As an example we could have original filter ~Q(child__name=\'foo\').
We would get here with filter_expr = child__name, prefix = child and
can_reuse is a set of joins usable for filters in the original query.
We will turn this into equivalent of:
WHERE NOT (pk IN (SELECT parent_id FROM thetable
WHERE name = \'foo\' AND parent_id IS NOT NULL))
It might be worth it to consider using WHERE NOT EXISTS as that has
saner null handling, and is easier for the backend\'s optimizer to
handle.'

def split_exclude(self, filter_expr, prefix, can_reuse, names_with_path):

    query = Query(self.model)
    query.where.add(query.build_filter(filter_expr), AND)
    query.bump_prefix()
    query.clear_ordering(True)
    (trimmed_prefix, contains_louter) = query.trim_start(names_with_path)
    query.remove_inherited_models()
    if self.is_nullable(query.select[0].field):
        (alias, col) = query.select[0].col
        query.where.add((Constraint(alias, col, query.select[0].field), 'isnull', False), AND)
    condition = self.build_filter((('%s__in' % trimmed_prefix), query), current_negated=True, branch_negated=True, can_reuse=can_reuse)
    if contains_louter:
        or_null_condition = self.build_filter((('%s__isnull' % trimmed_prefix), True), current_negated=True, branch_negated=True, can_reuse=can_reuse)
        condition.add(or_null_condition, OR)
    return condition
