Fix topological sort

Fixes https://github.com/django/django/pull/3525
Good catch.