Fix topological sort

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