Fix topological sort

Fixes https://github.com/django/django/pull/3525
I'd keep this on one line for better readability