code: def sort_dependencies(objects):
      from django.db.models import get_model
      model_dependencies = []
      models = set()
      model_list = set()
      objs_by_model = defaultdict(list)
      for o in objects:
          model = o.__class__
          objs_by_model[model].append(o)
          model_list.add(model)
      for model in model_list:
          models.add(model)
          if hasattr(model, 'natural_key'):
              deps = getattr(model.natural_key, 'dependencies', [])
              if deps:
                  deps = [get_model(*d.split('.')) for d in deps]
          else:
              deps = []
          for field in itertools.chain(model._meta.fields, model._meta.many_to_many):
              if hasattr(field.rel, 'to') and field.rel.to != model:
                  deps.append(field.rel.to)
          model_dependencies.append((model, deps))
      model_dependencies.reverse()
      model_list = []
      while model_dependencies:
          skipped = []
          changed = False
          while model_dependencies:
              model, deps = model_dependencies.pop()
              found = True
              for candidate in ((d not in models or d in model_list) for d in deps):
                  if not candidate:
                      found = False
              if found:
                  model_list.append(model)
                  changed = True
              else:
                  skipped.append((model, deps))
          if not changed:
              raise CommandError("Can't resolve dependencies for %s in serialized app list." %
                  ', '.join('%s.%s' % (model._meta.app_label, model._meta.object_name)
                  for model, deps in sorted(skipped, key=lambda obj: obj[0].__name__))
              )
          model_dependencies = skipped
      sorted_results = []
      for model in model_list:
          sorted_results.extend(objs_by_model[model])
      return sorted_results