                      dep = self._resolve_dependency(dep)[0]
                      if dep[0] == app_label:
                          for op2 in ops:
                              if self.check_dependency(op2, dep):
                                  dependency_graph[op].add(op2)
  
              # we use a stable sort for deterministic tests & general behavior
              self.generated_operations[app_label] = stable_topological_sort(
                  ops, dependency_graph
              )
  
      def _optimize_migrations(self):
          # Add in internal dependencies among the migrations
          for app_label, migrations in self.migrations.items():
              for m1, m2 in zip(migrations, migrations[1:]):
 
</s> remove             # construct a dependency graph for intra-app dependencies
            dependency_graph = {op: set() for op in ops}
 </s> add             ts = TopologicalSorter() </s> remove             dependency_graph.setdefault(head, set())
 </s> add             ts.add(head) </s> remove                     dependency_graph[item].add(head)
 </s> add                     ts.add(item, head) </s> remove         dependency_graph = defaultdict(set)
 </s> add         ts = TopologicalSorter()
                                ts.add(op, op2)
            self.generated_operations[app_label] = list(ts.static_order())
                      dep = self._resolve_dependency(dep)[0]
                      if dep[0] == app_label:
                          for op2 in ops:
                              if self.check_dependency(op2, dep):
                                ts.add(op, op2)
            self.generated_operations[app_label] = list(ts.static_order())
                                ts.add(op, op2)
            self.generated_operations[app_label] = list(ts.static_order())
                                ts.add(op, op2)
            self.generated_operations[app_label] = list(ts.static_order())
                                ts.add(op, op2)
            self.generated_operations[app_label] = list(ts.static_order())
                                ts.add(op, op2)
            self.generated_operations[app_label] = list(ts.static_order())
                                ts.add(op, op2)
            self.generated_operations[app_label] = list(ts.static_order())
  
      def _optimize_migrations(self):
          # Add in internal dependencies among the migrations
          for app_label, migrations in self.migrations.items():
              for m1, m2 in zip(migrations, migrations[1:]):
keep keep keep keep replace replace replace replace replace replace keep keep keep keep keep
 Fixed #32528 -- Replaced django.utils.topological_sort with graphlib.TopologicalSort().

graphlib.TopologicalSort() is available since Python 3.9. 
django/db/migrations/autodetector.py